JButton为什么不显示?

问题描述 投票:0回答:2

我试图制作一个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);
    }
}
java swing jframe jpanel jbutton
2个回答
1
投票

您从未真正将其添加到任何内容。

  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
    }

0
投票

尝试将JButton添加到类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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.