我刚接触Java,正在尝试开发一个基本的swing应用程序。我想在JFrame上设置按钮的位置。我试过这样做,但做不到这是我的代码。我正在使用eclipse进行开发。
public class MyUI extends JFrame {
JButton button1 = new JButton("Click");
JTextField tb1 = new JTextField(5);
JPanel panel1 = new JPanel();
public MyUI() {
super("Test");
setVisible(true);
this.setLayout(null);
panel1.setLayout(null);
panel1.setVisible(true);
button1.setVisible(true);
panel1.add(button1);
add(panel1);
panel1.setLocation(10, 10);
button1.setLocation(10, 10);
setDefaultCloseOperation(EXIT_ON_CLOSE);
button1.addActionListener(this);
}
public static void main(String[] args) {
MyUI gui = new MyUI();
gui.setSize(400, 300);
}
}发布于 2012-09-13 21:22:26
1.为什么要将两个JComponents放在同一个Bounds中
panel1.setLocation(10, 10);
button1.setLocation(10, 10); 2.了解Initials Thread
3.public class MyUI extends JFrame {
应该是
public class MyUI extends JFrame implements ActionListener{ 4.不要扩展JFrame,创建一个局部变量
5.setVisible(true);应该(在此表单中)是MyUI()构造函数中的最后一行代码
6.setVisible(true);是一个重要问题,您查看了JFrame,然后添加了JComponent
7.不要使用NullLayout,使用适当的LayoutManager,在删除this.setLayout(null);和panel1.setLayout(null);的情况下,添加的JComponents可能是可见的
8.在构造函数中使用setVisible(true)之前的pack()作为最后两行代码
编辑(使用built_in LayoutManagers、用于JFrame的BorderLayout和用于JPanel的FlowLayout )
import java.awt.event.*;
import javax.swing.*;
public class MyUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton button1 = new JButton("Click");
private JTextField tb1 = new JTextField(5);
private JPanel panel1 = new JPanel();
public MyUI() {
super("Test");
panel1.add(tb1);
panel1.add(button1);
add(panel1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
button1.addActionListener(this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyUI testing = new MyUI();
}
});
}
}发布于 2012-09-13 21:40:30
看不到您的面板和按钮,因为它们的大小为零。添加如下内容:
panel1.setSize(100, 100);
button1.setSize(80, 30);或者使用更方便同时设置位置和大小的setBounds方法:
panel1.setBounds(10, 10, 100, 100);
button1.setBounds(10, 10, 80, 30);发布于 2012-09-14 01:59:41
我想提出一些建议,虽然这不是对你问题的直接回答,但在我看来仍然很重要……
你可以使用NetBeans团队在2005年开发的Group Layout,使用起来很棒……现在尝试使用谷歌免费提供的Windows Builder Pro……您可以立即启动和运行您的应用程序......
https://stackoverflow.com/questions/12407103
复制相似问题