java 如何将 JButton 添加到 JFrame?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32941499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add JButton to JFrame?
提问by Ryan Hardin
At the moment this program displays a frame with a circle in its center. I tried to add a JButton to the frame so I could implement an action listener later to display the circle when pressed, but right now I'm having trouble actually showing the button. Can anybody tell me how and why this is happening?
目前这个程序显示一个中心有一个圆圈的框架。我尝试向框架添加一个 JButton,以便稍后我可以实现一个动作侦听器以在按下时显示圆圈,但现在我在实际显示按钮时遇到了麻烦。谁能告诉我这是如何以及为什么会发生?
import javax.swing.JComponent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.geom.*;
public class SimonShape extends JFrame {
private JFrame f;
private JPanel p;
private JButton b1;
private JLabel lab;
public static void main(String[] args) {
new SimonShape();
}
public SimonShape() {
f = new JFrame("Simon Says");
f.setVisible(true);
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
p.setBackground(Color.GRAY);
b1 = new JButton("Click Here to Begin!");
p.add(b1);
f.add(p);
f.setLocationRelativeTo(null);
f.add(new DrawStuff(), BorderLayout.CENTER);
}
public class DrawStuff extends JComponent {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Graphics2D g3 = (Graphics2D) g;
Graphics2D g4 = (Graphics2D) g;
Graphics2D g5 = (Graphics2D) g;
// assume d == 145 && e == 90
g2.setPaint(Color.GREEN);
g2.fill(new Arc2D.Double(150, 150, 200, 200, 145, 90, Arc2D.PIE));
g3.setPaint(Color.BLUE);
g3.fill(new Arc2D.Double(150, 150, 200, 200, 235, 90, Arc2D.PIE));
g4.setPaint(Color.RED);
g4.fill(new Arc2D.Double(150, 150, 200, 200, 325, 90, Arc2D.PIE));
g5.setPaint(Color.YELLOW);
g5.fill(new Arc2D.Double(150, 150, 200, 200, 55, 90, Arc2D.PIE));
}
}
}
回答by Ryan Hardin
Problem is you have put the JFrame on the screen prior to adding JButton to it.
问题是您在添加 JButton 之前已将 JFrame 放在屏幕上。
Either you can move this line f.setVisible(true);
to the bottom(last line) of the constructor.
您可以将此行移动f.setVisible(true);
到构造函数的底部(最后一行)。
Or you may put this line f.revalidate();
after adding all required components to the JFrame.
或者您可以f.revalidate();
在将所有必需的组件添加到 JFrame 之后放置这一行。
回答by Dakshinamurthy Karra
Change f.add(p);
and add a location for the border layout. And also move your setVisible
call to the end - after adding all the components.
更改f.add(p);
并添加边框布局的位置。setVisible
在添加所有组件之后,还将您的呼叫移到最后。