我想在同一帧中使用2个面板。但按钮不起作用?我怎么做?我想在一个面板上放几个按钮,其他面板会做一些其他的东西。
public class TestingPage extends JFrame {
JFrame frame=new JFrame();
JPanel panel01;
JPanel panel02;
JButton bttn1;
/**
* @param args
*/
public TestingPage(){
super("Test");
setBounds(700,700,650,500);
setVisible(true);
setLayout(new BorderLayout());
Container cont=frame.getContentPane();
panel01=new JPanel();
panel02=new JPanel();
cont.add(panel01,BorderLayout.EAST);
cont.add(panel02,BorderLayout.WEST);
//setLayout(new BorderLayout());
bttn1=new JButton("Button");
bttn1.setBounds(77, 75, 100,26);
add(bttn1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Runnable guiCreator= new Runnable(){
@Override
public void run (){
TestingPage page=new TestingPage();
}
};
javax.swing.SwingUtilities.invokeLater(guiCreator);
}
}
答案 0 :(得分:3)
你有三个问题......
setVisible
。这是众所周知的常见问题。如果您需要在设置可见后向框架添加内容,则需要调用revalidate
以确保更新布局JFrame
,但您创建了另一个JFrame
并使用其内容窗格添加您的组件,但让TestingPage
可见......
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestingPage extends JFrame {
// JFrame frame = new JFrame();
JPanel panel01;
JPanel panel02;
JButton bttn1;
public TestingPage() {
super("Test");
setBounds(700, 700, 650, 500);
setLayout(new BorderLayout());
Container cont = getContentPane();
panel01 = new JPanel();
panel02 = new JPanel();
cont.add(panel01, BorderLayout.EAST);
cont.add(panel02, BorderLayout.WEST);
//setLayout(new BorderLayout());
bttn1 = new JButton("Button");
panel01.add(bttn1);
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Runnable guiCreator = new Runnable() {
@Override
public void run() {
TestingPage page = new TestingPage();
}
};
javax.swing.SwingUtilities.invokeLater(guiCreator);
}
}