我试图在java中进行GUI编程,并希望在Jpanel中绘制一个矩形.代码没有给出任何错误,但我无法在GUI中获得矩形.有人可以告诉我以下代码中缺少的内容.我相信这很简单,所以请保持温柔.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloWorldGUI2 {
private static class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private static class RectDraw extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(230,80,10,10);
g.setColor(Color.RED);
g.fillRect(230,80,10,10);
}
}
public static void main(String[] args) {
JPanel content = new JPanel();
RectDraw newrect= new RectDraw();
JButton okButton= new JButton("OK");
JButton clearButton= new JButton("Clear");
ButtonHandler listener= new ButtonHandler();
okButton.addActionListener(listener);
clearButton.addActionListener(listener);
content.add(okButton);
content.add(clearButton);
content.add(newrect);
JFrame window = new JFrame("GUI Test");
window.setContentPane(content);
window.setSize(250,100);
window.setLocation(100,100);
window.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
Hov*_*els 11
你的newrect RectDraw的大小可能会非常小,可能是[0,0],因为它已经使用JPanel添加到FlowLayout并且没有设置preferredSize.考虑重写其getPreferredSize()方法并返回合适的Dimension,以便可以看到它的绘图.
private static class RectDraw extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(230,80,10,10);
g.setColor(Color.RED);
g.fillRect(230,80,10,10);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H); // appropriate constants
}
}
Run Code Online (Sandbox Code Playgroud)
也,
paintComponent方法应该受到保护,而不是公开的@Override在您的方法覆盖之前不要忘记使用.| 归档时间: |
|
| 查看次数: |
39407 次 |
| 最近记录: |