Java 调用paintComponent的正确方法是什么?
我是JavaGUI新手,我试图让这个程序在点击按钮时显示一个正方形。因为repaint()在paintComponent(图形g)上不起作用,所以不会发生任何事情。我已经搜索过了,有些人说使用了事件调度线程,但我仍然很困惑Java 调用paintComponent的正确方法是什么?,java,swing,jframe,paintcomponent,Java,Swing,Jframe,Paintcomponent,我是JavaGUI新手,我试图让这个程序在点击按钮时显示一个正方形。因为repaint()在paintComponent(图形g)上不起作用,所以不会发生任何事情。我已经搜索过了,有些人说使用了事件调度线程,但我仍然很困惑 import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class Ham extends JFrame implements ActionLis
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Ham extends JFrame implements ActionListener
{
JPanel p1;
JButton b1;
public Ham(){
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1 = new JPanel();
b1 = new JButton("Check");
b1.addActionListener(this);
p1.add(b1);
add(p1, BorderLayout.NORTH);
setVisible(true);
}
public void actionPerformed (ActionEvent e){
if(e.getSource() == b1){
repaint();
}
}
public void paintComponent(Graphics g){
g.setColor(Color.BLUE);
g.fillRect(100,100,50,50);
}
}
JFrame没有paintComponent()方法 自定义绘制是通过覆盖
JPanel
(或JComponent)的paintComponent()
方法来完成的。您还应该重写面板的getPreferredSize()
方法以返回合理的值。然后将面板添加到框架中
然后可以在面板上调用repaint()
,并调用paintComponent()方法
有关更多信息和示例,请阅读上Swing教程的部分 JFrame没有paintComponent()方法 自定义绘制是通过覆盖
JPanel
(或JComponent)的paintComponent()
方法来完成的。您还应该重写面板的getPreferredSize()
方法以返回合理的值。然后将面板添加到框架中
然后可以在面板上调用repaint()
,并调用paintComponent()方法
有关更多信息和示例,请阅读上Swing教程的部分 我很抱歉花时间回答这个问题。我刚刚注意到你在论坛上问了10个问题,一次也不需要花时间接受你问题的答案。我猜你不感谢我们给你的帮助。很抱歉,我刚刚发现你能做到。非常感谢你的帮助。我很抱歉花时间回答这个问题。我刚刚注意到你在论坛上问了10个问题,一次也不需要花时间接受你问题的答案。我猜你不感谢我们给你的帮助。对不起,我刚发现你能做到。真的很感谢我们的帮助。