paintComponent() 的问题

Problems with paintComponent()

问题涉及我项目中的 2 个 classes:主体和绘图 class。 main class 创建 JFrame 并在其中放置 2 个 JPanel。 第一个 JPanel 包含您输入数字的 JTextFields 和 select 不同选项的 JButtons,还有一个开始按钮和一个重置按钮。第二个 JPanel 是绘图的实例 class.

第二个class,绘图class应该先画出图形,然后再画出数字的视觉表示(triangle/trapezoid)。基本上应该在启动项目后立即绘制图表(直到现在没问题),然后在按下开始按钮后绘制数字(没有任何反应)。 以下是与问题相关的部分代码。

Public class MainMenu extends JFrame implements ActionListener {
  private JPanel mainPanel;      
  public static void main(String[] args) {
    MainMenu app = new MainMenu();
    app.setVisible(true);
    app.setResizable(false);
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    app.setBounds(250, 200, 1200, 600); 
  }

  public MainMenu() {
    drawing = new DrawingTool();
    mainPanel.add(drawing);    //draws the graphs on launch
    //extra code. not relevant
  }

  public void Run(){
    // more code
    drawing.updateVariables(numberA,numberB,numberC,operation,precision);
  }

第二个class

public class DrawingTool extends JPanel{
boolean numbersUpdated=false;
public void updateVariables(Nr nrA, Nr nrB, Nr nrC, int op, int prec){
  fzzyA = nrA;
  fzzyB = nrB;
  fzzyC = nrC;
  operation = op;
  precision = prec;
}
public void paintComponent(Graphics g){
    //draw the graphs - this works
    if(numbersUpdated){
    //draw the numbers
    }
 }

此外,如果我想通过按下重置按钮将绘图 JPanel 重置为仅绘制图形的位置,仅将 numbersUpdates 设置为 false 是否可行?

then draw the numbers after the start button is pressed(nothing happens).

每当您更改 Swing 组件的 属性 时,您需要调用 repaint() 来告诉组件自行绘制。

因此,在您的 updateVariables(...) 方法中,您需要在方法末尾添加一个 repaint() 语句。