我试图在框架gui上添加一个按钮 我尝试制作一个面板并将其添加到该面板,但它不起作用。 请帮忙!
这是我的代码:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button;
JPanel panel;
// my error lines are under the "panel" and "button"
// it says i must implement the variables. what does that mean???
panel.add(button);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
答案 0 :(得分:4)
变化:
JButton button;
JPanel panel;
为:
JButton button = new JButton();
JPanel panel = new JPanel();
您还可以在String
构造函数中传递JButton()
值,以便在JButton
上显示该字符串值。
示例: JButton button = new JButton("I am a JButton");
答案 1 :(得分:1)
示例代码:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
// Create JButton and JPanel
JButton button = new JButton("Click here!");
JPanel panel = new JPanel();
// Add button to JPanel
panel.add(button);
// And JPanel needs to be added to the JFrame itself!
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
<强>输出:强>
注意:强>
new JButton("...");
和new JPanel()
getContentPane().add(...);
答案 2 :(得分:0)
如果可以更改此程序,还可以调整按钮位置
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class agui extends JFrame
{
agui()
{
setTitle("My GUI");
setSize(400,400);
setLayout(null);
JButton button = new JButton("Click Here..!");
button.setBounds(50,100,100,50); /*Distance from left,
Distance from top,length of button, height of button*/
add(button);
setVisible(true);
}
public static void main(String[] args)
{
JFrame agui = new agui();
}
}