我怎样才能创建一个 JButton?
How can i create a JButton?
创建 JButton 并将其设置为 Visible 后,我不明白为什么我在 Window.. 中看不到它:/
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Window extends JFrame{
public static int width = 350;
public static int height = 480;
public static void main (String args[]) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(width, height);
window.setVisible(true);
window.setTitle("Virtual World");
window.setLocationRelativeTo(null);
window.setResizable(false);
window.getContentPane().setBackground(new Color(80,80,240));
JButton enter = new JButton();
enter.setVisible(true);
}
}
正如@Tunaki 在评论中已经提到的,您需要先将 JButton 添加到面板中。
试试这个
public class Test extends JFrame{
public static int width = 350;
public static int height = 480;
public static void main (String args[]) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(width, height);
window.setTitle("Virtual World");
window.setLocationRelativeTo(null);
window.setResizable(false);
window.getContentPane().setBackground(new Color(80,80,240));
JButton enter = new JButton("Ok");
enter.setVisible(true);
JPanel panel = new JPanel();
window.add(panel);
panel.add(enter);
window.setVisible(true);
}
}
您需要在 JFrame
中添加 JPanel
。然后您可以将 JButton
添加到 JPanel
。
最简单的方法是在代码末尾添加以下行:
window.getContentPane().add( enter );
这将向您的 JFrame 的内容面板添加一个按钮。
但请注意,您最终会得到一个 window 大小的按钮 ;)
创建 JButton 并将其设置为 Visible 后,我不明白为什么我在 Window.. 中看不到它:/
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Window extends JFrame{
public static int width = 350;
public static int height = 480;
public static void main (String args[]) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(width, height);
window.setVisible(true);
window.setTitle("Virtual World");
window.setLocationRelativeTo(null);
window.setResizable(false);
window.getContentPane().setBackground(new Color(80,80,240));
JButton enter = new JButton();
enter.setVisible(true);
}
}
正如@Tunaki 在评论中已经提到的,您需要先将 JButton 添加到面板中。
试试这个
public class Test extends JFrame{
public static int width = 350;
public static int height = 480;
public static void main (String args[]) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(width, height);
window.setTitle("Virtual World");
window.setLocationRelativeTo(null);
window.setResizable(false);
window.getContentPane().setBackground(new Color(80,80,240));
JButton enter = new JButton("Ok");
enter.setVisible(true);
JPanel panel = new JPanel();
window.add(panel);
panel.add(enter);
window.setVisible(true);
}
}
您需要在 JFrame
中添加 JPanel
。然后您可以将 JButton
添加到 JPanel
。
最简单的方法是在代码末尾添加以下行:
window.getContentPane().add( enter );
这将向您的 JFrame 的内容面板添加一个按钮。 但请注意,您最终会得到一个 window 大小的按钮 ;)