[英]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.