PaintComponent不使用JButton - FIXED

时间:2016-08-31 20:08:46

标签: java layout jframe jbutton

编辑:谢谢大家,你真的帮帮我了。我需要做的最后一件事是将面板布局设为null,这样JButton就可以移动了。谢谢!

我的paintComponents内容没有显示在我的程序屏幕上,我想我可能做错了布局,但我无法弄清楚为什么我的drawString“计算器”没有显示出来。这是我的代码(我从另一个名为Launcher的类启动Window):

    package uusi.projekti.juttu;

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Window implements Runnable{

    public Window() {

        JButton button = new JButton("=");
        button.setBounds(530, 510, 50, 50);
        button.setLayout(null);
        button.setVisible(true);

        JPanel panel = new JPanel();

        JFrame frame = new JFrame("Title");

    //  frame.setLayout(new FlowLayout());
        frame.setVisible(true);
        frame.setSize(600, 600);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.add(new drawPanel());
        frame.add(panel);

        panel.setLayout(null);
        panel.add(button);
        panel.add(new drawPanel());
    }

    public class drawPanel extends JPanel {
        public void paintComponent(Graphics g) {
            Font font = new Font("Arial", 60, 60);
            g.setFont(font);
            g.drawString("Calculator", 100, 100);
        }
    }

    public void run() {
    }
}

这是Launcher.java

package uusi.projekti.juttu;

public class Launcher {

    public static void main(String[] args) {
        new Window();
    }
}

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

public class Window实现了Runnable {

public Window() {

    JButton button = new JButton("=");
    button.setBounds(530, 510, 50, 50);
    button.setLayout(null);
    button.setVisible(true);

    JPanel panel = new drawPanel();

    JFrame frame = new JFrame("Title");

//  frame.setLayout(new FlowLayout());
    frame.setVisible(true);
    frame.setSize(600, 600);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.add(panel);

    panel.add(button);
}