JFrame frame = new JFrame("Picture");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
display = new JPanel();
if(event.getSource().equals(birthday)){
background = new JLabel(bday);
display.add(background);
}
else if(event.getSource().equals(cake)){
picture = new JLabel(pastry, SwingConstants.LEFT);
display.add(picture);
}
else if(event.getSource().equals(input)){
word = new JLabel(text);
word.setHorizontalTextPosition(SwingConstants.RIGHT);
word.setVerticalTextPosition(SwingConstants.CENTER);
display.add(word);
}
frame.setPreferredSize (new Dimension(450, 350));
frame.getContentPane().add(display);
frame.pack();
frame.setVisible(true);
这是我的独立类中的ActionListener类的一部分。我有一个comboBox / cardLayout。因此,当我从一个comboBox标签中单击一个按钮(蛋糕),并从另一个另一个comboxBox标签中单击另一个按钮(生日)时,会出现两个框架。我希望这些东西在SAME框架上,但我无法弄清楚如何这样做。
答案 0 :(得分:4)
而是每次调用action perform方法创建框架的新实例时,需要创建一个共享实例...
public class OneFrameToRuleThemAll {
public static void main(String[] args) {
new OneFrameToRuleThemAll();
}
public OneFrameToRuleThemAll() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
private JFrame frame;
private static final String FRUIT[] = new String[] {
"Banana",
"Apple",
"Manga",
"Pear"
};
public TestPane() {
JButton button = new JButton("Fruit");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (frame == null) {
frame = new JFrame("Fruits basket");
frame.setSize(100, 200);
frame.setLayout(new GridLayout(0, 1));
frame.setLocationRelativeTo(TestPane.this);
frame.setVisible(true);
}
int index = (int)Math.round(Math.random() * (FRUIT.length - 1));
frame.add(new JLabel(FRUIT[index]));
frame.getContentPane().validate();
}
});
setLayout(new GridBagLayout());
add(button);
}
}
}