![](/img/trans.png)
[英]Java Swing GUI application is completly blank with no content at all, while buttons are added to the panel
[英]Why my Swing GUI is not showing all the buttons added?
誰能告訴我為什么我的 Java Swing GUI 沒有顯示框架上所有添加的按鈕? 就像當我添加 5 個按鈕時,它只顯示 4,如果是 4,則顯示 3。
請讓我知道這有什么問題。
我也嘗試在面板上添加它們,但 GUI 沒有顯示一個。
package p2;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Gui extends JFrame {
public Gui(){
//Frame
JFrame fr=new JFrame("Calculator");
//Panel
JPanel p=new JPanel();
p.setBounds(10, 10, 200, 200);
p.setBackground(Color.cyan);
//Button
JButton b1=new JButton("Button 1");
b1.setBounds(20, 20, 40, 30);
JButton b2=new JButton("Button 2");
b2.setBounds(20, 80, 40, 30);
fr.add(p);
p.add(b1);p.add(b2);
fr.setVisible(true);
fr.setSize(300, 400);
fr.setLayout(null);
}
public static void main(String[] args) {
new Gui();
}
}
這是因為以下行:
fr.setLayout(null);
只需將其刪除即可。
首先:不要使用“null”布局。 但是當你使用任何布局時,你必須在添加任何組件之前設置它。
要解決您的問題,您只需向上移動fr.setLayout(null)
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Gui extends JFrame {
public Gui() {
// Frame
JFrame fr = new JFrame("Calculator");
// Panel
JPanel p = new JPanel();
p.setBounds(10, 10, 200, 200);
p.setBackground(Color.cyan);
// Button
JButton b1 = new JButton("Button 1");
b1.setBounds(20, 20, 40, 30);
JButton b2 = new JButton("Button 2");
b2.setBounds(20, 80, 40, 30);
fr.setLayout(null); // set layout before adding of components.
fr.add(p);
p.add(b1);
p.add(b2);
fr.setVisible(true);
fr.setSize(300, 400);
}
public static void main(String[] args) {
new Gui();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.