2016-10-12 4 views
1

В программе, которую я пишу, я хочу, чтобы 10 текстовых полей были выровнены по вертикали. Вместо этого я получаю это:Swing GridBagLayout act out

What it looks like

код здесь:

import java.awt.*; 
import java.util.Random; 
import javax.swing.*; 
import java.awt.event.*; 

public class Gsb extends JFrame { 

    JTextField word1; 
    JTextField word2; 
    JTextField word3; 
    JTextField word4; 
    JTextField word5; 
    JTextField word6; 
    JTextField word7; 
    JTextField word8; 
    JTextField word9; 
    JTextField word10; 
    JButton gofor; 
    JButton rego; 
    JTextArea Stuff; 
    JPanel panel; 
    JPanel texts; 
    JPanel buttons; 
    JButton Quit; 
    JPanel bigt; 
    String[] words = new String[20]; 
    static int[] randnums = new int[20]; 

    int i = 0; 

    public static void main(String[] args) { 

     new Gsb(); 
     Random Rand = new Random(); 

     int counter = 0; 
     int rand; 
     int[] pick = new int[20]; 
     for(int i = 0; i < 20; i++) 
     { 
      rand = Rand.nextInt(20) + 1; 
      if (CheckForDuplicate(pick, rand, counter)) 
      { 
       pick[i] = rand; 
       counter++; 
      } 
      else 
      { 
       i--; 
      } 
     } 
     for(int p = 0; p < 20; p++) { 
      randnums[p] = pick[p] - 1; 
     } 
    } 

    static boolean CheckForDuplicate(int[] array, int number, int counter) 
    { 
     for (int i = 0; i < counter; i++) 
     { 
      if (array[i] == number) 
      { 
       return false; 
      } 
     } 

     return true; 
    } 

    public Gsb() { 

     Toolkit tk = Toolkit.getDefaultToolkit(); 
     Dimension dim = tk.getScreenSize(); 

     int xPos = (dim.width/2) - (this.getWidth()/2); 
     int yPos = (dim.height/2) - (this.getHeight()/2); 
     this.setLocation(xPos, yPos); 
     GridBagConstraints c = new GridBagConstraints(); 
     GridBagConstraints d = new GridBagConstraints(); 
     this.setSize(500, 500); 
     this.setTitle("checker"); 
     this.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     panel = new JPanel(); 
     texts = new JPanel(); 
     buttons = new JPanel(); 
     bigt = new JPanel(); 
     word1 = new JTextField(10); 
     word2 = new JTextField(10); 
     word3 = new JTextField(10); 
     word4 = new JTextField(10); 
     word5 = new JTextField(10); 
     word6 = new JTextField(10); 
     word7 = new JTextField(10); 
     word8 = new JTextField(10); 
     word9 = new JTextField(10); 
     word10 = new JTextField(10); 
     gofor = new JButton("BONANZA!"); 
     rego = new JButton("Restart"); 
     Stuff = new JTextArea(40, 40); 
     Quit = new JButton("Exit"); 
     Stuff.setLineWrap(true); 
     Stuff.setWrapStyleWord(true); 
     Stuff.setText("welcome to the google search bonanza! first user write 10 random words and press BONANZA!"); 
     JScrollPane useless = new JScrollPane(Stuff, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
     panel.setLayout(new GridBagLayout()); 
     texts.setLayout(new GridBagLayout()); 
     buttons.setLayout(new GridBagLayout()); 
     bigt.setLayout(new GridBagLayout()); 
     c.fill = GridBagConstraints.CENTER; 
     d.fill = GridBagConstraints.RELATIVE; 

     d.gridx = 0; 
     d.gridy = 0; 
     texts.add(word1, d); 
     d.gridx = 0; 
     d.gridy = 1; 
     texts.add(word2, d); 
     d.gridx = 0; 
     d.gridy = 2; 
     texts.add(word3, d); 
     d.gridx = 0; 
     d.gridy = 3; 
     texts.add(word4, d); 
     d.gridx = 0; 
     d.gridy = 4; 
     texts.add(word5, d); 
     d.gridx = 0; 
     d.gridy = 5; 
     texts.add(word6, d); 
     d.gridx = 0; 
     d.gridy = 6; 
     texts.add(word7, d); 
     d.gridx = 0; 
     d.gridy = 7; 
     texts.add(word8, d); 
     d.gridx = 0; 
     d.gridy = 8; 
     texts.add(word9, d); 
     d.gridx = 0; 
     d.gridy = 9; 
     texts.add(word10); 
     c.gridx = 10; 
     c.gridy = 0; 
     buttons.add(gofor,c); 
     c.gridx = 9; 
     c.gridy = 0; 
     buttons.add(Quit,c); 
     c.gridx = 8; 
     c.gridy = 0; 
     buttons.add(rego ,c); 
     Bonanza bonanzer = new Bonanza(); 
     Bonanzatwo bon2 = new Bonanzatwo(); 
     Reset Reseter = new Reset(); 
     Exit Exiter = new Exit(); 
     rego.addActionListener(Reseter); 
     gofor.addActionListener(bonanzer); 
     gofor.addActionListener(bon2); 
     Quit.addActionListener(Exiter); 
     bigt.add(Stuff); 
     c.gridheight = 20; 
     c.gridx = 0; 
     c.gridy = 0; 
     panel.add(texts, c); 

     panel.add(buttons); 


     panel.add(bigt); 
     panel.add(useless); 
     this.add(panel); 
     this.setExtendedState(JFrame.MAXIMIZED_BOTH); 
     this.setUndecorated(true); 
     this.setVisible(true); 
     this.setTitle("The Google search bonanza"); 
    } 

в основном, если это не было ясно, им будет что-то вроде этого:

What I'm going for

+0

1) Для лучшей помощи рано, оставить [MCVE] или [Short, Self Содержащийся, правильный пример] (http://www.sscce.org/). 2) Используйте логическую и согласованную форму отступающих кодовых строк и блоков. Отступы предназначены для того, чтобы поток кода стал проще следовать! 3) Заменить «Toolkit tk = Toolkit.getDefaultToolkit(); .. this.setLocation (xPos, yPos); 'с' this.setLocationRelativeTo (null); 'для того же эффекта. Или лучше. 'this.setLocationByPlatform (true);' .. –

+0

.. 4) Предоставить ASCII-искусство или простой чертеж * предполагаемого * макета GUI при минимальном размере и ** если изменить размер, с большей шириной и высотой. ** ** последний **, чтобы показать, как должно быть назначено дополнительное пространство. –

+0

спасибо, я буду помнить об этом в следующий раз! –

ответ

2

Дон Не используйте GridBagLayout, когда вы хотите создать сетку чего-то - используйте GridLayout, здесь с 1 столбцом и 0 (fo r переменное число). Вы можете создать JPanel только для JTextFields, дать ему GridLayout, а затем добавить этот JPanel в основной графический интерфейс с помощью GridBagLayout, если хотите, но здесь ключ состоит в том, чтобы вложить JPanels, каждый из которых использует свой собственный макет.

Другое предложение, когда я вижу такие переменные, как:

JTextField word1; 
JTextField word2; 
JTextField word3; 
JTextField word4; 
JTextField word5; 
JTextField word6; 
JTextField word7; 
JTextField word8; 
JTextField word9; 
JTextField word10; 

Я думаю, не ей действительно хочет использовать массив или ArrayList здесь? Или, возможно, JTable.

Кроме того, вы добавляете JTextArea в JScrollPane, но затем добавляете JTextArea, а не JScrollPane в графический интерфейс.

Например:

import java.awt.BorderLayout; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import javax.swing.*; 

public class Gsb2 extends JPanel { 
    private static final int WORD_FIELD_COUNT = 10; 
    private static final int COL_SIZE = 10; 
    private static final int TA_ROWS = 40; 
    private static final int TA_COLS = 40; 
    private JTextField[] wordFields = new JTextField[WORD_FIELD_COUNT]; 
    private int rows; 
    private JTextArea stuffArea = new JTextArea(TA_ROWS, TA_COLS); 

    public Gsb2() { 
     JPanel wordFieldsPanel = new JPanel(new GridLayout(0, 1)); 
     for (int i = 0; i < wordFields.length; i++) { 
      wordFields[i] = new JTextField(COL_SIZE); 
      wordFieldsPanel.add(wordFields[i]); 
     } 

     JPanel wrapWordFieldsPanel = new JPanel(new GridBagLayout()); 
     wrapWordFieldsPanel.add(wordFieldsPanel); 

     JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0)); 
     buttonPanel.add(new JButton(new MyAction("Restart", KeyEvent.VK_R))); 
     buttonPanel.add(new JButton(new MyAction("Exit", KeyEvent.VK_X))); 
     buttonPanel.add(new JButton(new MyAction("BONANZA!", KeyEvent.VK_B))); 

     JScrollPane scrollPane = new JScrollPane(stuffArea); 

     JPanel rightPanel = new JPanel(new BorderLayout(5, 5)); 
     rightPanel.add(wrapWordFieldsPanel, BorderLayout.CENTER); 
     rightPanel.add(buttonPanel, BorderLayout.PAGE_END); 

     setLayout(new BorderLayout(5, 5)); 
     setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); 
     add(rightPanel, BorderLayout.LINE_START); 
     add(scrollPane, BorderLayout.CENTER); 

    } 

    private class MyAction extends AbstractAction { 
     public MyAction(String name, int mnemonic) { 
      super(name); 
      putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // TODO add code 

     } 
    } 

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

     JFrame frame = new JFrame("Gsb2"); 
     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(() -> createAndShowGui()); 
    } 
} 

OK, OK, чтобы "матч спецификации", используйте BoxLayout:

import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import javax.swing.*; 

public class Gsb3 extends JPanel { 
    private static final int WORD_FIELD_COUNT = 10; 
    private static final int COL_SIZE = 10; 
    private static final int TA_ROWS = 40; 
    private static final int TA_COLS = 40; 
    private JTextField[] wordFields = new JTextField[WORD_FIELD_COUNT]; 
    private int rows; 
    private JTextArea stuffArea = new JTextArea(TA_ROWS, TA_COLS); 

    public Gsb3() { 
     JPanel wordFieldsPanel = new JPanel(new GridLayout(0, 1)); 
     for (int i = 0; i < wordFields.length; i++) { 
      wordFields[i] = new JTextField(COL_SIZE); 
      wordFieldsPanel.add(wordFields[i]); 
     } 

     JPanel wrapWordFieldsPanel = new JPanel(new GridBagLayout()); 
     wrapWordFieldsPanel.add(wordFieldsPanel); 

     JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0)); 
     buttonPanel.add(new JButton(new MyAction("Restart", KeyEvent.VK_R))); 
     buttonPanel.add(new JButton(new MyAction("Exit", KeyEvent.VK_X))); 
     buttonPanel.add(new JButton(new MyAction("BONANZA!", KeyEvent.VK_B))); 
     buttonPanel.setMaximumSize(buttonPanel.getPreferredSize()); 

     JScrollPane scrollPane = new JScrollPane(stuffArea); 

     setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); 
     setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); 
     add(wrapWordFieldsPanel); 
     add(Box.createHorizontalStrut(5)); 
     add(buttonPanel); 
     add(Box.createHorizontalStrut(5)); 
     add(scrollPane); 

    } 

    private class MyAction extends AbstractAction { 
     public MyAction(String name, int mnemonic) { 
      super(name); 
      putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // TODO add code 

     } 
    } 

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

     JFrame frame = new JFrame("Gsb2"); 
     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(() -> createAndShowGui()); 
    } 
} 
+1

Я предпочитаю, чтобы этот код помещал кнопки под текстовыми полями, но обратите внимание, что он не соответствует «spec». (2) изображение. –

+1

@ AndrewThompson: Понял. См. Изменение, использующее BoxLayout. –

+1

Pft .. теперь вы заставляете меня хотеть снова проголосовать. ;) –

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