【问题标题】:Open another panel inside another panel after pressing button按下按钮后在另一个面板中打开另一个面板
【发布时间】:2016-03-10 03:49:12
【问题描述】:

我收到一条错误消息,说我没有添加一些方法(执行的操作),但我已经添加了。我无法打开 panel2。

public class panel1 extends JPanel implements ActionListener(){
    private panel2 p2=new panel2();
    private JButton button;

    public panel1(){
    button=new JButton("open panel2");
    add(button,BorderLayout.BEFORE_FIRST_LINE);
    button.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent ae) {

            add(p2);

        }

    });

  }

}

【问题讨论】:

  • panel1需要实现ActionListener接口描述的actionPerformed方法
  • 但不是已经有@Override public void actionPerformed(ActionEvent ae) { add(p2); } ?对不起,我是编程新手
  • 不,那是匿名类的实现

标签: java user-interface jpanel action panel


【解决方案1】:

考虑这些变化:

public class panel1 extends JPanel implements ActionListener(){
    private panel2 p2=new panel2();
    private JButton button;

    public panel1(){
    button=new JButton("open panel2");
    add(button,BorderLayout.BEFORE_FIRST_LINE);
    button.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent ae) {
            //Add readability: Where to add?
            panel1.this.add(p2);
        }

    });

  }

  //THIS HERE makes your panel1 implment ActionListener
  @Override
  public void actionPerformed(ActionEvent ae) {

  }
}

还请注意常见的 Java 命名约定 - 类名应以大写字母开头 (Panel1 extends JPanel)

【讨论】:

  • 谢谢!这消除了错误。虽然它仍然没有打开第二个面板..
  • 也许你应该添加 (panel2, BorderLayout.CENTER) 什么的?
【解决方案2】:
You can check the below code for replacing jpanel without switching jframe.  



contentPanel.removeAll();
        contentPanel.repaint();
        contentPanel.revalidate();
        contentPanel.add(//add your panel here);
        contentPanel.repaint();
        contentPanel.revalidate();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多