好吧,我今天的编程练习有点麻烦。
练习内容如下:
(使用FlowLayout管理器)编写满足以下要求的程序:
按钮应该命名为"Button 1","Button 2“等等。
我想我在将面板添加到框架时遇到了一些问题,因为当我运行程序时,它显示了一个空的框架。
这是我的密码。
import javax.swing.*;
import java.awt.*;
public class Exercise12_1 extends JFrame {
public Exercise12_1() {
setLayout(new FlowLayout());
JFrame frame = new JFrame(" Exercise 12_1 ");
frame.setLayout(new FlowLayout());
// Create two panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
panel1.setLayout(new FlowLayout());
panel2.setLayout(new FlowLayout());
// Add three buttons to each panel
panel1.add(new JButton(" Button 1 "));
panel1.add(new JButton(" Button 2 "));
panel1.add(new JButton(" Button 3 "));
panel2.add(new JButton(" Button 4 "));
panel2.add(new JButton(" Button 5 "));
panel2.add(new JButton(" Button 6 "));
// Add panels to frame
frame.add(panel1);
frame.add(panel2);
}
public static void main(String[] args) {
Exercise12_1 frame = new Exercise12_1();
frame.setTitle(" Exercise 12_1 ");
frame.setSize(600, 100);
frame.setLocationRelativeTo(null); // center frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}如果你们中的一些人花点时间来帮助我,我会非常感激的。谢谢。
发布于 2013-11-10 13:30:51
您的主要方法创建一个框架:
Exercise12_1 frame = new Exercise12_1();然后让它清晰可见。
这个“Exercise12_1”框架的构造函数创建另一个框架,并将面板添加到另一个框架中:
JFrame frame = new JFrame(" Exercise 12_1 ");
frame.setLayout(new FlowLayout());构造函数不应该创建另一个框架。它应该将面板添加到this:正在构建的框架中,然后使其可见。
另外,您不应该使用setSize(),而应该使用pack(),以便根据它包含的所有组件的首选大小使框架具有最合适的大小。
发布于 2013-11-10 13:32:05
检查一下这个:
import javax.swing.*;
import java.awt.*;
public class Exercise12_1 extends JFrame {
public Exercise12_1() {
setLayout(new FlowLayout());
//JFrame frame = new JFrame(" Exercise 12_1 ");
this.setLayout(new FlowLayout());
// Create two panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
panel1.setLayout(new FlowLayout());
panel2.setLayout(new FlowLayout());
// Add three buttons to each panel
panel1.add(new JButton(" Button 1 "));
panel1.add(new JButton(" Button 2 "));
panel1.add(new JButton(" Button 3 "));
panel2.add(new JButton(" Button 4 "));
panel2.add(new JButton(" Button 5 "));
panel2.add(new JButton(" Button 6 "));
// Add panels to frame
this.add(panel1);
this.add(panel2);
}
public static void main(String[] args) {
Exercise12_1 frame = new Exercise12_1();
frame.setTitle(" Exercise 12_1 ");
frame.setSize(600, 100);
frame.setLocationRelativeTo(null); // center frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}发布于 2013-11-10 13:29:59
您可以使用类似this.getContentPane().add(Panel1)这样的代码来添加面板。
变化
frame.add(panel1);
frame.add(panel2);至
this.getContentPane().add(panel1);
this.getContentPane().add(panel2);然后它就会起作用了。
https://stackoverflow.com/questions/19890196
复制相似问题