2013-03-11 63 views
0

我有一个具有面板的小程序。在面板中添加一个按钮,点击该按钮将移除当前面板,并将新面板添加到当前的Applet中。如何使用ActionListener在同一个Applet中添加新面板

但我没有得到所需的输出!

我想从ActionListener中用新面板替换当前添加到Applet的显示面板。

请告诉错误!

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JApplet; 
import javax.swing.JPanel; 

public class Init extends JApplet { 

    public Display ref; 
    public NewDisplay ref2; 

    public class Display extends JPanel implements ActionListener { 

     public Display() { 
      initComponents(); 
     } 

     private void initComponents() { 
      jButton1 = new javax.swing.JButton(); 
      jButton1.setText("New Game"); 
      add(jButton1); 
      jButton1.addActionListener(this); 

     } 
     public javax.swing.JButton jButton1; 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      String x = e.getActionCommand(); 
      if (x.equals("New Game")) { 
       System.out.println("clicked"); 
       //ref.setVisible(false); 
       this.removeAll(); 
       //add(ref2); 
       add(ref2); 
       invalidate(); 
       revalidate(); 
       repaint(); 
      } 
     } 
    } 

    public class NewDisplay extends JPanel { 

     public NewDisplay() { 
      setSize(800, 600); 
     } 

     @Override 
     public void paintComponent(Graphics g) { 
      g.setColor(Color.RED); 
      g.fillRect(0, 0, 800, 600); 
     } 
    } 

    @Override 
    public void init() { 
     ref = new Display(); 
     ref2 = new NewDisplay(); 
     add(ref); 
     setSize(800,600); 

    } 
} 
+0

你是否缩小了问题范围?例如:它是否到达actionPerformed()方法?它输出“点击”吗? – 2013-03-11 20:55:08

+0

是的,它输出“点击”! – Snehasish 2013-03-11 21:22:54

回答

3

您不应该使用setSize()方法来设置组件的大小。

布局管理器使用组件的首选大小。您应该重写面板的getPreferredSzie()方法以返回所需的大小。

public class NewDisplay extends JPanel { 

    public NewDisplay() { 
    // setSize(800, 600); 
    } 

    @Override 
    public Dimension getPreferredSize() 
    { 
     return new Dimension(800, 600); 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     g.setColor(Color.RED); 
     g.fillRect(0, 0, 800, 600); 
    } 
} 

或者更好的解决方案是使用卡片布局,并将面板进出。见How to Use Card Layout

+0

我认为每次我在Swing上看到一个关于布局的问题时,每个人的回答都是“更好的解决方案就是使用<我的首选布局>!” :-) – 2013-03-11 21:05:25

+0

在这段代码中,我们将删除当前面板的组件,并将新面板添加到当前面板! 这是对的吗? – Snehasish 2013-03-12 05:12:11

+0

如果是,我如何删除当前面板并将新面板添加到Applet中?请澄清 !! – Snehasish 2013-03-12 05:12:47