我希望在按下按钮时绘制一个矩形,但它似乎不起作用。这是我的代码:
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 已正确构造,但未添加到框架中。提前致谢