我有点卡住了。我应该显示2个按钮和1个标签,但我的程序没有显示它们。如果您有任何想法,那就太棒了。我正在使用eclipse,代码正在编译和运行。这是代码。
/** This is the driver class of the program.
* Here is the main method with the JFrame.
* class name RunFurniture.class
* @author Kiril Anastasov
* @date 18/03/2012
*/
import java.awt.*;
import javax.swing.*;
public class RunRurniture
{
/**
* @param args
*/
public static void main(String[] args)
{
JFrame application = new JFrame();
PanelFurniture panel = new PanelFurniture();
application.add(panel);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setSize(600,450);
application.setLocationByPlatform(true);
application.setVisible(true);
}
}
/** Here is the GUI of the program.
* class name PanelFurniture.class
* @author Kiril Anastasov
* @date 18/03/2012
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PanelFurniture extends JPanel implements ActionListener
{
JLabel label;
JButton a,b;
JPanel centerPanel, eastPanel;
public void actionPerformed(ActionEvent ae)
{
this.setLayout(new BorderLayout());
centerPanel = new JPanel();
//centerPanel.setLayout();
this.add(centerPanel, BorderLayout.CENTER);
eastPanel = new JPanel(new GridLayout(1,3));
label = new JLabel();
b = new JButton("Move");
eastPanel.add(b);
eastPanel.add(label);
a = new JButton("ee");
eastPanel.add(a);
//this.add(eastPanel);
this.add(eastPanel, BorderLayout.EAST);
}
}
答案 0 :(得分:2)
您只在actionPerformed中将组件添加到面板,并且您从未将其注册为侦听器,因此永远不会显示它。相反,在构造函数/ init方法中添加它们:
public class PanelFurniture extends JPanel
{
JLabel label;
JButton a,b;
JPanel centerPanel, eastPanel;
public void init()
{
this.setLayout(new BorderLayout());
centerPanel = new JPanel();
//centerPanel.setLayout();
this.add(centerPanel, BorderLayout.CENTER);
eastPanel = new JPanel(new GridLayout(1,3));
label = new JLabel();
b = new JButton("Move");
eastPanel.add(b);
eastPanel.add(label);
a = new JButton("ee");
eastPanel.add(a);
this.add(eastPanel, BorderLayout.EAST);
}
}
并在创建面板后调用init()
:
PanelFurniture panel = new PanelFurniture();
panel.init();
application.add(panel);
另外,确保UI是EDT上的构造函数:
SwingUtils.invokeLater(new Runnable() {
@Override
public void run() {
JFrame application = new JFrame();
PanelFurniture panel = new PanelFurniture();
application.add(panel);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setSize(600,450);
application.setLocationByPlatform(true);
application.setVisible(true);
}
});