繁体   English   中英

如何添加没有冲突的JButton和JLabel?

[英]How do I add JButtons and JLabels without conflicts?

当我尝试将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);
    }
}

您可能应该使用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之类的布局管理器。

如果您真的不想使用layoutmanager,请使用JPanel。 一个JFrame只能容纳一个组件,这就是您的问题。 将JPanel放在JFrame内,然后将组件放入JPanel。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM