我希望在按下按钮时绘制一个矩形,但它似乎不起作用。 这是我的代码:
package draw.rect;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class DR extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DR frame = new DR();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DR() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 458, 312);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnDrawRrect = new JButton("Draw Rrect");
btnDrawRrect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.print("hello");
RectangleComponent r2 = new RectangleComponent();
contentPane.add(r2);
r2.revalidate();
contentPane.revalidate();
}
});
btnDrawRrect.setBounds(10, 11, 89, 23);
contentPane.add(btnDrawRrect);
}
}
package draw.rect;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
public class RectangleComponent extends JComponent {
Rectangle rect;
public RectangleComponent()
{
rect = new Rectangle(50, 50, 120, 130);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.draw(rect);
}
}
问题在于,当调用操作事件监听器时,JComponent 已正确构造,但未添加到框架中。 提前致谢
最佳答案
您正在使用空布局,并且在这样做时,您完全负责使用容器设置添加到空布局的任何组件的大小和位置。您忽略了这一责任,并且没有为添加的 JComponent 指定大小或位置,因此在将其添加到容器时,由于其大小为 0,因此无法看到它。为了向自己证明这一点,请添加 System.out。 println() 会打印出添加的组件是否可见及其边界是什么,您将亲眼看到。您的第二个问题是,您在添加组件后没有调用 repaint()
,尽管这并不总是必要的,也不是当前问题的原因。一个快速修复方法是设置新添加组件的边界,但我不建议您这样做。相反,我建议:
- 我强烈建议您不要使用空布局,因为它们会使您的代码不灵活并且非常难以维护和升级。
- 阅读教程并使用布局管理器。
- 从容器中删除或添加组件后,调用容器上的
revalidate()
,然后调用repaint()
。
关于java - Windows构建器 : How to draw a component when press a button?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15183097/