【问题标题】:PaintComponent not working with JButtons - FIXEDPaintComponent 无法与 JButton 一起使用 - 已修复
【发布时间】:2017-01-08 13:13:07
【问题描述】:

编辑:谢谢大家,你们真的帮助了我。我需要做的最后一件事是使面板布局为空,以便 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();
    }
}

【问题讨论】:

  • 你的主要方法在哪里?
  • 编辑了原帖,因为代码在 cmets 中没有格式化

标签: java layout jframe jbutton


【解决方案1】:

试试这样的:

公共类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);
}

【讨论】:

  • 现在出现计算器字符串和按钮,但我无法更改按钮的位置?我是否需要使用其他类型的代码来更改按钮的位置或其他布局?
猜你喜欢
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 2019-01-02
  • 2011-09-14
  • 1970-01-01
  • 2013-03-08
  • 2019-01-12
  • 1970-01-01
相关资源
最近更新 更多