如何在没有冲突的情况下添加JButton和JLabel?

时间:2015-03-21 19:05:12

标签: java swing jframe jbutton jlabel

当我尝试将JButton和JLabel添加到JFrame中时,它们彼此冲突,其中所有JButton都会消失,只有JLabel可见。由于某种原因,JLabel将转到JFrame的最左侧,而不是我设置的所需位置。我是GUI相关材料的新手,我愿意从这些错误中吸取教训。

这是我的代码:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Windowb extends JFrame{
    static String title = "This is a JFrame";
    static int width = 500;
    static int height = 400;

    private static final int BUTTON_LOCATION_X = 46;
    private static final int BUTTON_LOCATION_Y = 80;

    public static void main(String[]args){
        Windowb simple = new Windowb(title, width, height);
        JPanel p = new JPanel(); 
        p.setLayout(null);
        JLabel c1 = new JLabel("Name: ");
        JButton b1 = new JButton("Name:");
        JButton b2 = new JButton("Grade:");
        JButton b3 = new JButton("GPA");
        b1.setBounds(BUTTON_LOCATION_X, BUTTON_LOCATION_Y, 90, 20);
        b2.setBounds(50, 170, 90, 20);
        b3.setBounds(50, 240, 90, 20);
        c1.setLocation(100, 250);

        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                JOptionPane.showMessageDialog(null, "ActionListener is working!");
            }

        });


        b2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            JOptionPane.showMessageDialog(null, "The second one works too!");
            }
        });

        b3.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                JOptionPane.showMessageDialog(null, "Surprise!");
            }
        });
        p.add(b1); 
        p.add(b2); 
        p.add(b3);
        simple.add(p);
        simple.add(c1);
    }

    public Windowb(String t, int w, int h){
        setVisible(true);
        setResizable(true);
        setSize(w, h);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(500, 100);
        setTitle(t);
    }
}

1 个答案:

答案 0 :(得分:2)

您可能应该使用LayoutManager。请参阅布局管理器教程:http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

布局管理器使用setBounds()来定位组件。您可以将LayoutManager设置为null并自己定位组件,但是窗口调整大小的东西不会以这种方式为您处理(即,组件和空间不会相应地缩放)。如果你想保持理智,那就不要使用GridBag布局中的构建!它会让你疯狂!对于更复杂的布局,请使用http://www.miglayout.com/http://www.jgoodies.com/freeware/libraries/forms/。对于简单的布局,请使用BorderLayout等布局管理器。

如果您真的不想使用布局管理器,请使用JPanel。 JFrame只能容纳一个组件以解决您的问题。将JPanel放在JFrame中并将您的组件放在JPanel中。