2015-09-27 3 views
1

У меня есть проект, который требует от меня создать простой графический интерфейс, который имеет jTextArea вверху, а JButtons добавлен с 0 до 9. Это довольно просто сделать, однако программа требует от меня центр 0 в нижней части. Следующий код выполняет это, однако мне нужно использовать Grid Layout вместо flowLayout. Когда я пишу это с помощью GridLayout, я не могу получить 0, чтобы выровнять что угодно, кроме левой. Как я могу использовать GridLayout и центрировать 0?Центральные кнопки на контейнере java

public class CalculatorProject { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    GUI gui = new GUI(); 
} 

} 

public class GUI extends JFrame { 

public GUI() { 
    JFrame aWindow = new JFrame("Calculator"); 
    aWindow.setBounds(30, 30, 175, 215); // Size 
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JTextField jta = new JTextField(20); 
    FlowLayout flow = new FlowLayout(); // Create a layout manager 
    flow.setHgap(5);     // Set the horizontal gap 
    flow.setVgap(5); 
    flow.setAlignment(FlowLayout.CENTER); 
    Container content = aWindow.getContentPane(); // Get the content pane 
    content.setLayout(new GridLayout(4,3,5,5)); 

    content.setLayout(flow); // Set the container layout mgr 
    content.add(jta); 
    // Now add six button components 
    int array[] = {7, 8, 9, 4, 5, 6, 1, 2, 3, 0}; 
    for (int i = 0; i <= 9; i++) { 
     content.add(new JButton("" + array[i])); 

    } 
    aWindow.setVisible(true); // Display the window 
} 
} 
+0

Почему вы не используете BorderLayout? Это просто. – CodeRunner

+0

@CodeRunner: ему понадобится использовать JPANel с BorderLayout с GranLayout JPanel, вложенным в него. –

+0

ОК. См. Мой отзыв мой ответ тоже. Это может помочь вам. – CodeRunner

ответ

4

Добавить пустой JPanel в квадраты сетки, которые вы хотели бы быть пустым.

int array[] = {7, 8, 9, 4, 5, 6, 1, 2, 3, 0}; 
for (int i = 0; i <= 8; i++) { 
    content.add(new JButton("" + array[i])); 
} 
content.add(new JPanel()); 
content.add(new JButton("" + array[9])); 
content.add(new JPanel()); // not needed, but fills the last square of the grid 

Редактировать: Удалено дополнительное непреднамеренное появление слова «пусто».

3

Пусть макеты и простой 2D-массив строк помогут вам. Например, если вы объявляете массив 2D Строка для текста кнопки следующим образом:

private static final String[][] TEXTS = { 
     {"7", "8", "9"}, 
     {"4", "5", "6"}, 
     {"1", "2", "3"}, 
     {"", "0", ""} 
    }; 

А затем цикл через массив, создавая кнопки, где текст не "" пуст, и пустой JLabel, где он пуст, и поместите кнопки в GridLayout, используя JPanel, вы там. Я также рекомендую вложить JPanels, внешний с помощью BorderLayout, удерживая JTextField вверху - BorderLayout.PAGE_START, а другой JPanel с помощью GridLayout, удерживая кнопки и помещая в положение BorderLayout.CENTER внешнего BorderLayout с помощью JPanel. Например:

import java.awt.BorderLayout; 
import java.awt.GridLayout; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.*; 

public class Gui2 extends JPanel { 
    private static final String[][] TEXTS = { 
     {"7", "8", "9"}, 
     {"4", "5", "6"}, 
     {"1", "2", "3"}, 
     {"", "0", ""} 
    }; 
    private List<JButton> buttons = new ArrayList<>(); 
    private JTextField textField = new JTextField(5); 

    public Gui2() { 
     int rows = TEXTS.length; 
     int cols = TEXTS[0].length; 
     int gap = 2; 
     JPanel gridPanel = new JPanel(new GridLayout(rows, cols, gap, gap)); 
     for (int r = 0; r < TEXTS.length; r++) { 
      for (int c = 0; c < TEXTS[r].length; c++) { 
       String text = TEXTS[r][c]; 
       if (!text.trim().isEmpty()) { 
        JButton button = new JButton(text); 
        gridPanel.add(button); 
        buttons.add(button); 
        // add ActionListener here 
       } else { 
        // empty String, so add a blank place-holder JLabel 
        gridPanel.add(new JLabel()); 
       } 
      } 
     } 

     setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap)); 
     setLayout(new BorderLayout(gap, gap)); 
     add(textField, BorderLayout.PAGE_START); 
     add(gridPanel, BorderLayout.CENTER); 
    } 

    private static void createAndShowGui() { 
     Gui2 mainPanel = new Gui2(); 

     JFrame frame = new JFrame("Gui2"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGui(); 
      } 
     }); 
    } 
} 
5

Используя BorderLayout, все просто. Добавьте TextField на север. Теперь просто добавьте девять кнопок в JPanel. Добавьте JPanel в центр. Наконец, добавьте кнопку Zero на юг.

public class CalculatorProject { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
       @Override 
       public void run() { 
        GUI gui = new GUI(); 
       } 
      }); 

    } 

    } 

    class GUI extends JFrame { 

    GUI() { 
     super("Calculator"); 
     setBounds(30, 30, 160, 190); // Size 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JTextField jta = new JTextField(20); 
     JPanel panel = new JPanel(); 
     setLayout(new BorderLayout(5, 5)); 
     Container content = this.getContentPane(); // Get the content pane 
     content.add(jta, BorderLayout.NORTH); 
     // Now add six button components 
     int array[] = {7, 8, 9, 4, 5, 6, 1, 2, 3}; 
     for (int i = 0; i < 9; i++) { 
      panel.add(new JButton("" + array[i])); 

     } 
     content.add(panel, BorderLayout.CENTER); 
     content.add(new JButton("0"), BorderLayout.SOUTH); 
     setVisible(true); // Display the window 
    } 
    } 

Результат

enter image description here

Смежные вопросы