按钮没有显示在Jframe上

时间:2017-06-07 04:37:48

标签: java swing jframe

// Creating buttons
JButton b1 = new JButton();
    b1.setText("Add");
    b1.setSize(100, 130);
    b1.setLocation(330, 70);
    b1.setBackground(Color.red);
    b1.setVisible(true);

// Creating second button       
JButton b2 = new JButton();
    b2.setText("Add");
    b2.setSize(100,100);
    b2.setLocation(0, 0);
    b2.setBackground(Color.blue);
    b2.setVisible(true);

//adding buttons to Jframe
f.add(b1);
f.add(b2);

按钮在我运行程序时不会出现,或者有时它们会出现,但完全占用整个JFrame

1 个答案:

答案 0 :(得分:2)

猜猜#1

就像关于这个主题的几乎所有问题一样,在将组件添加到UI之前,您正在调用f.setVisible(true)

所以,这样的事情应该解决它

// In some other part of your code you've not provided us
//f.setVisible(true);

JButton b1 = new JButton();
b1.setText("Add");
b1.setBackground(Color.red);

JButton b2 = new JButton();
b2.setText("Add");
b2.setBackground(Color.blue);

f.add(b1);
f.add(b2);
f.setVisible(true);

猜猜#2

您没有更改JFrame的默认布局管理器,因此它仍在使用BorderLayout

这样的事情至少应该允许显示两个按钮而不会相互重叠

f.setLayout(new FlowLayout());
f.add(b1);
f.add(b2);
f.setVisible(true);

我建议花一些时间浏览Laying out Components within a Container以获取更多详情

相关问题