2
  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 类的一部分。我有一个组合框/卡片布局。因此,当我从一个组合框标签单击一个按钮(蛋糕),从另一个组合框标签单击另一个按钮(生日)时,出现了两个框架。我希望这些东西在同一个框架上,但我不知道该怎么做。

4

1 回答 1

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);

        }

    }

}
于 2013-01-13T03:47:24.960 回答