我正在创建一个应用程序来实现算法,但在此之前我需要让paint方法正常工作 我有一个按钮,点击它我调用测试方法,我得到输出"值设置"来自println但重绘方法没有被执行。
但同样的事情是在另一个简单的应用程序中工作。
任何帮助都会很棒
顺便说一句,我是电子学家,所以我不太了解编程
This is the class for painting
`
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
public class Draw extends JPanel {
private java.util.List<Rectangle> rectangles =
new ArrayList<Rectangle>();
public Draw() {
setOpaque(true);
setBackground(Color.WHITE);
rectangles = new ArrayList<Rectangle>();
}
public void test(){
rectangles.add(new Rectangle(10,10,10,10));
rectangles.add(new Rectangle(20,20,10,10));
rectangles.add(new Rectangle(30,30,10,10));
rectangles.add(new Rectangle(40,40,10,10));
rectangles.add(new Rectangle(50,50,10,10));
rectangles.add(new Rectangle(60,60,10,10));
this.setValues(rectangles);
System.out.println("in test class");
}
public void setValues(java.util.List<Rectangle> rectangles) {
this.rectangles = rectangles;
repaint();
System.out.println("values set!!");
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(5, 5, 100, 300);
for (Rectangle rectangle : rectangles) {
g.drawRect(rectangle.x, rectangle.y,rectangle.width, rectangle.height);
}
System.out.println("WORKING");
}
}
`
GUI的类
import javax.swing.*;
import java.awt.*;
public class Design extends JFrame{
Draw Draw = new Draw();
static HandlerClass handler = new HandlerClass();
public void DisplayGUI(){
JFrame frame = new JFrame("title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
frame.setContentPane(content);
.//Contains code that adds different buttons to Different panels
.
.
.
. content.add(Draw, BorderLayout.CENTER);
frame.setSize(775,600);
frame.setVisible(true);
}
主要班级
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Program extends JFrame{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new Design().DisplayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
处理程序类
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class HandlerClass implements ActionListener{
private String string ="";
ExampleOne ExampleOne = new ExampleOne();
Draw draw = new Draw();
public void actionPerformed(ActionEvent event){
string = ((JButton) event.getSource()).getActionCommand();
if(string == "Example 1"){
ExampleOne.run();
}
}
}
class ExampleOne{
Draw draw = new Draw();
public void run(){
System.out.println("in example one class");
draw.test();
}
}