【问题标题】:Why is the JButton not showing?为什么 JButton 不显示?
【发布时间】:2020-01-04 18:42:10
【问题描述】:

我尝试制作一个 JButton 并将其添加到 JFrame,但它没有出现。没有错误。我对可以添加点对象但不能添加 JButton 的事实感到更加困惑。因此,任何有关如何修复它的帮助将不胜感激。

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);
    }
}

【问题讨论】:

  • 不要扩展 JFrame。这是糟糕的技术。只需使用一个实例。请查看this post 做图形。

标签: java swing jframe jpanel jbutton


【解决方案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
    }

【讨论】:

    【解决方案2】:

    尝试将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);
        }
    

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 2016-02-16
      相关资源
      最近更新 更多