这是我的代码
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
public class Test extends JFrame{
private JButton by;
private JButton bn;
JLabel startQuestion;
public Test() {
JPanel p = new JPanel();
by = new JButton("Yes");
bn = new JButton("No");
startQuestion = new JLabel("Would you like to start?");
p.setLayout(null);
by.setBounds(180, 250, 70, 45);
bn.setBounds(250, 250, 70, 45);
startQuestion.setLocation(195, 240);
p.add(by);
p.add(bn);
add(startQuestion);
add(p);
setDefaultCloseOperation(3);
setSize(500, 500);
setVisible(true);
}
public static void main(String...args) {
new Test();
}
}
没有语法错误,但是我的Jlabel没有添加(按钮工作正常)。我不想从null更改布局,因为我希望能够定义按钮和标签的位置。有谁知道为什么这不起作用?
答案 0 :(得分:2)
此问题与JLabel won't show with JPanel.setLayout(null). Why?
类似要在此处回答,请添加如下所示的行:
startQuestion.setBounds(150, 150, 200, 20);
答案 1 :(得分:0)
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
public class Test extends JFrame{
private JButton by;
private JButton bn;
JLabel startQuestion;
public Test() {
JPanel p = new JPanel();
by = new JButton("Yes");
bn = new JButton("No");
startQuestion = new JLabel("Would you like to start?");
//p.setLayout(null);
by.setBounds(180, 250, 70, 45);
bn.setBounds(250, 250, 70, 45);
startQuestion.setLocation(195, 240);
p.add(by);
p.add(bn);
add(startQuestion);
add(p);
setDefaultCloseOperation(3);
setSize(500, 500);
setVisible(true);
}
public static void main(String...args) {
new Test();
}
}
您需要发表评论setlayout(null);