เมื่อฉันพยายามเพิ่ม JButton และ JLabel ลงใน JFrame ทั้งคู่ขัดแย้งกันโดยที่ JButtons ทั้งหมดจะหายไปและมีเพียง 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);
}
}
setBounds
ตรวจสอบขอบเขตการตั้งค่าb1,b2,b3
ของคุณ นอกจากนี้อย่าพยายามใช้เลย์เอาต์แบบ null แทน ให้ฝึกฝนกับตัวจัดการเลย์เอาต์อื่น ๆ ที่จัดทำโดย java docs.oracle.com/javase/tutorial/uiswing/layout/using HTML - person Vighanesh Gursale   schedule 21.03.2015Windowb
คืออะไร คุณกำลังพยายามเพิ่มส่วนประกอบบนวัตถุsimple
ซึ่งเป็นของWindowb
โปรดปฏิบัติตามกฎง่ายๆ ในการเพิ่มส่วนประกอบ โปรดอ่านบทความเหล่านี้ docs.oracle.com/javase/tutorial/uiswing/ start/index.html - person Vighanesh Gursale   schedule 21.03.2015