为什么 JButton 不显示?
Why is the JButton not showing?
我尝试制作一个 JButton 并将其添加到 JFrame,但它没有出现。没有错误。我更困惑的是我可以添加点对象而不是 JButtton。因此,我们将不胜感激任何有关如何修复它的帮助。
import javax.swing.*;
import java.awt.*;
public class JavaGraphics extends JFrame {
JavaGraphics() throws HeadlessException {
setSize(600, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(new DrawArea());
setVisible(true);
}
public static void main(String[] args) {
new JavaGraphics();
}
}
class DrawArea extends JPanel {
Point A = null;
Point B = null;
JButton button;
public DrawArea() {
A = new Point(100, 200);
B = new Point(200, 300);
button = new JButton("Text");
button.setBounds(0, 0, 100, 50);
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.drawLine(A.x, A.y, B.x, B.y);
g.drawString("A", A.x, A.y);
g.drawString("B", B.x, B.y);
}
}
你从来没有真正将它添加到任何东西中。
public DrawArea() {
A = new Point(100, 200);
B = new Point(200, 300);
button = new JButton("Text");
button.setBounds(0, 0, 100, 50);
this.add(button); // add this line
}
尝试将 JButton 添加到 class DrawArea:
的构造函数中
public DrawArea() {
A = new Point(100, 200);
B = new Point(200, 300);
button = new JButton("Text");
button.setBounds(0, 0, 100, 50);
add(button);
}
我尝试制作一个 JButton 并将其添加到 JFrame,但它没有出现。没有错误。我更困惑的是我可以添加点对象而不是 JButtton。因此,我们将不胜感激任何有关如何修复它的帮助。
import javax.swing.*;
import java.awt.*;
public class JavaGraphics extends JFrame {
JavaGraphics() throws HeadlessException {
setSize(600, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(new DrawArea());
setVisible(true);
}
public static void main(String[] args) {
new JavaGraphics();
}
}
class DrawArea extends JPanel {
Point A = null;
Point B = null;
JButton button;
public DrawArea() {
A = new Point(100, 200);
B = new Point(200, 300);
button = new JButton("Text");
button.setBounds(0, 0, 100, 50);
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.drawLine(A.x, A.y, B.x, B.y);
g.drawString("A", A.x, A.y);
g.drawString("B", B.x, B.y);
}
}
你从来没有真正将它添加到任何东西中。
public DrawArea() {
A = new Point(100, 200);
B = new Point(200, 300);
button = new JButton("Text");
button.setBounds(0, 0, 100, 50);
this.add(button); // add this line
}
尝试将 JButton 添加到 class DrawArea:
的构造函数中 public DrawArea() {
A = new Point(100, 200);
B = new Point(200, 300);
button = new JButton("Text");
button.setBounds(0, 0, 100, 50);
add(button);
}