窗口调整大小时调整JComboBox的大小

时间:2014-10-06 18:53:01

标签: java jcombobox

我有一个带有topPanel,centerPanel和bottomPanel的JFrame。 在topPanel中,我有一个有六列和一行的网格。我有固定的列大小。 在右边的列中,我有一个JComboBox。

我的问题是,当我调整窗口大小(使其变小或变大)时,JComboBox不会调整大小(这意味着当窗口变得足够小时它会消失,或者当窗口变大时我会在它周围获得大量空间)。我希望JComboBox在窗口时调整大小。

我的老师说只有一行代码可以修复它,我试图整夜搞清楚。你能帮助我吗?

import java.awt.*;
import javax.swing.*;

public class Program extends JFrame {

public Program(String title) {     
    super(title);
    setLayout(new BorderLayout());     
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
    setSize(840, 500);                
    initComponents();                 
    setVisible(true);                 
}

private void initComponents() {
    String[] boxOptions = new String[] {"Man", "Woman"};

    JPanel topPanel = new JPanel(new GridLayout(1,6));  
    JPanel centerPanel = new JPanel();                  
    JPanel bottomPanel = new JPanel(new GridLayout(1,3));

    JPanel greenPanel = new JPanel();
    JPanel bluePanel= new JPanel();
    JPanel blackPanel = new JPanel();
    JPanel redPanel= new JPanel();
    JPanel yellowPanel = new JPanel();
    JPanel comboBoxPanel = new JPanel();

    JComboBox comboBox = new JComboBox(boxOptions);
    comboBox.setSelectedIndex(0);
    comboBox.setPreferredSize(new Dimension(140,40));

    greenPanel.setBackground(Color.GREEN);
    bluePanel.setBackground(Color.BLUE);
    blackPanel.setBackground(Color.BLACK);
    redPanel.setBackground(Color.RED);
    yellowPanel.setBackground(Color.YELLOW);

    greenPanel.setPreferredSize(new Dimension(140,40));
    bluePanel.setPreferredSize(new Dimension(140,40));
    blackPanel.setPreferredSize(new Dimension(140,40));
    redPanel.setPreferredSize(new Dimension(140,40));
    yellowPanel.setPreferredSize(new Dimension(140,40));
    comboBoxPanel.setPreferredSize(new Dimension(140,40));

    topPanel.setPreferredSize(new Dimension(0,40));

    comboBoxPanel.add(comboBox);

    topPanel.add(greenPanel);                               
    topPanel.add(bluePanel);                                
    topPanel.add(blackPanel);
    topPanel.add(redPanel);
    topPanel.add(yellowPanel);
    topPanel.add(comboBoxPanel);


    add(topPanel, BorderLayout.PAGE_START);              
    add(centerPanel, BorderLayout.CENTER);           
    add(bottomPanel, BorderLayout.PAGE_END);         
}

public static void main(String args[]) {
    new Program("Test");
}   
}

0 个答案:

没有答案