2013-06-27 2 views
4

Я хочу, чтобы это:Как правильно настроить этот графический интерфейс?

sketch

Я попытался это:

// Vertically center 
    formatbp.setLayout (new GridBagLayout()); // formatbp is a JPanel 
    GridBagConstraints gbc = new GridBagConstraints(); 
    gbc.gridx = 0; 
    gbc.gridy = GridBagConstraints.RELATIVE; 

    rbpanel.setLayout(new BoxLayout(rbpanel, BoxLayout.PAGE_AXIS)); // rbpanel is also a JPanel 
    rb = new ButtonGroup(); 
    rbpanel.add(new JLabel("Words are seperated by: ")); 

    rbLinesOrTabs.setSelected(true); 
    rb.add(rbLinesOrTabs); 
    rbpanel.add(rbLinesOrTabs); 
    rbLinesOrTabs.addActionListener(this); 

    rbotherpanel = new JPanel(new FlowLayout()); 
    rb.add(rbOther); 
    rbpanel.add(rbOther); 
    rbOther.addActionListener(this); 

    othercharfield.setEnabled(false); // Is going to be enabled when rbOther gets selected (and disabled again when rbLinesOrTabs is selected again), that is where the actionlisteners are for 
    rbotherpanel.add(othercharfield); 

    rbpanel.add(rbotherpanel); 

    formatbp.add(rbpanel,gbc); 
    formatbp.add(formatb,gbc); // formatb is the button 

(большинство объектов, где инициализируются ранее в коде)

Но это результат:

result1

Что я делаю неправильно?

EDIT: Я обнаружил, что я сделал ошибку здесь:

rbpanel.add(rbOther); 

Это должно было быть:

rbotherpanel.add(rbOther); 

Теперь я получаю:

result2

лучше, но Другой элемент не выравнивается правильно. (это немного вправо, как вы можете видеть)

+4

Чтобы лучше помочь, опубликуйте [SSCCE] (http://sscce.org/). –

+0

Не рекомендуется повторно использовать один и тот же экземпляр «GridBagConstraints» для нескольких компонентов. – predi

+0

@com. Мальчик, как вы получили алмазы вместо кругов? Кроме того, что такое первое программное обеспечение, с которым вы сделали этот макет (черный n белый) –

ответ

2

все-в-одном подход с использованием MigLayout (да, это действительно мой текущим любимый :-)

MigLayout layout = new MigLayout("debug", "[][]"); 
    JComponent content = new JPanel(layout); 
    content.add(new JLabel("Words are separated by: "), "span"); 
    JRadioButton radio = new JRadioButton("Lines or tabs"); 
    content.add(radio, "wrap"); 
    // split the cell so it will contain both the other button 
    // and the textfield 
    content.add(new JRadioButton("Other:"), "split 2"); 
    // get the right margin of the upper radiobutton 
    int rightMargin = radio.getInsets().right; 
    content.add(new JTextField(), "grow, wrap, " + 
     // remove the gap to the preceding radiobutton 
      "gapx 0, " + 
     // set the padding to compensate the right edge 
      "pad 0 0 0 -" + rightMargin + "px"); 
    content.add(new JButton("Format"), "span, center"); 
    showInFrame(content, "align to button text"); 

Визуальный результат тонких ухищрений в общей ячейке бит зависит от LAF. Выглядит хорошо в Windows, не так хорошо в Nimbus (последний выглядит лучше всего без какой-либо компенсации), поэтому вам нужно немного экспериментировать.

+0

[Работал!] (Http://i.imgur.com/dZj9isL.png) Спасибо! –

+0

Кстати, это выглядело отлично во всех L & F, которые я пробовал, включая Nimbus. –

2

Вы добавляете четыре вещи в rbPanel, что означает, что вы получите четыре строки (что похоже на пример скриншота). Другое и текстовое поле должны находиться в одной строке, поэтому вы должны поместить их в свою панель или использовать GridbagConstraints, чтобы правильно позиционировать все компоненты.

Используйте GridX и GridY вместо RELATIVE, так как это облегчает понимание кода.

0

Try ниже кода,

public static void main(String[] args) 
{ 
     SwingUtilities.invokeLater(new Runnable() 
     { 

      @Override 
      public void run() 
      { 
       JFrame frame = new JFrame(); 
       frame.setBounds(0, 0, 300, 300); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


       JPanel formatbp = new JPanel(); 
       formatbp.setLayout (new GridBagLayout()); // formatbp is a JPanel 
       GridBagConstraints gbc = new GridBagConstraints(); 
       gbc.gridx = 0; 
       gbc.gridy = GridBagConstraints.RELATIVE; 

       JPanel rbpanel = new JPanel(); 
       rbpanel.setLayout(new BoxLayout(rbpanel, BoxLayout.Y_AXIS)); // rbpanel is also a JPanel 
       ButtonGroup rb = new ButtonGroup(); 
       rbpanel.add(new JLabel("Words are seperated by: ")); 

       JRadioButton rbLinesOrTabs = new JRadioButton("line or tabs"); 
       rbLinesOrTabs.setSelected(true); 
       rb.add(rbLinesOrTabs); 
       rbpanel.add(rbLinesOrTabs); 
//    rbLinesOrTabs.addActionListener(this); 
       JRadioButton rbOther = new JRadioButton("others:"); 
       JPanel rbotherpanel = new JPanel(); 
       rb.add(rbOther); 
       rbotherpanel.add(rbOther); 
//    rbOther.addActionListener(this); 
       JTextField othercharfield = new JTextField("test", 4); 
//    othercharfield.setColumns(800); 
//    othercharfield.setEnabled(false); // Is going to be enabled when rbOther gets selected (and disabled again when rbLinesOrTabs is selected again), that is where the actionlisteners are for 
       rbotherpanel.add(othercharfield); 

       rbpanel.add(rbotherpanel); 

       formatbp.add(rbpanel,gbc); 
       JButton formatb = new JButton("format"); 
       formatbp.add(formatb,gbc); // formatb is the button 
       frame.getContentPane().add(formatbp); 
       frame.pack(); 
       frame.setVisible(true);     
      } 
     }); 

    }