【问题标题】:Why is no text shown within the JOptionPane when my paintComponent method is called?为什么调用我的 paintComponent 方法时 JOptionPane 中没有显示文本?
【发布时间】:2014-08-11 18:39:54
【问题描述】:

我正在尝试在用户输入无效输入时显示消息对话框。

当我尝试使用null 作为对话框的位置时,当输入 0 或负数时,对话框正确显示,但对话框中没有标题或文本。

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // draw lines

    endY = getHeight(); // bottom
    endX = getWidth(); // right side
    Input = Integer.parseInt(inputField.getText());

    if (Input > 0 ) {

        for (int beginY = getHeight() / 2; beginY <= endY; beginY += Input) {
            g.drawLine(0, beginY, endX, beginY);
        }

    } else {
        JOptionPane.showMessageDialog(null, "Please do not enter 0 or a negative number.", "Wrong input", JOptionPane.ERROR_MESSAGE);
    }
}

我尝试使用我的 JFrame 对象作为第一个参数,该对象已在不同的类中声明和初始化,并且有效。

但是,我希望能够在 paintComponent 方法的 JPanel 类中使用此代码,以便在绘制线条时向其添加 if/else 逻辑。

【问题讨论】:

    标签: java swing dialog


    【解决方案1】:

    每当 AWT EDT(Abstract Window Toolkit Event Dispatching Thread)中的某些内容时,都会调用 paintComponent 方法 认为组件需要重新绘制。那个方法是 经常和经常在你没想到它被调用的时候调用。 因此,不要在该方法的主体中显示 JOptionPane。你必须 从方法中取出该逻辑并在需要时显示它。

    你可以这样做,但这不是一个好的编程习惯:

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (canPaint) {
            // Do some painting if we can
            // Lets say an error occurred:
            // If the dialog is shown over the component then the component will
            // be redrawn. Now, we don't want this code to loop, so we set a
            // flag to control the "loop".
            canPaint = false;
    
            // Now we tell the AWT event queue that we want to show the message
            // whenever it get's a chance, because the Dialog won't be drawn
            // properly if it's called here.
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    showWarning();
                }
            });
        }
    }
    
    void showWarning() {
        javax.swing.JOptionPane.showMessageDialog(null, "Syntax Error : ", "Incorrect user input", javax.swing.JOptionPane.ERROR_MESSAGE);
    }
    

    但一般从不在paintComponent方法中做编程逻辑!

    欲了解更多信息,请参阅此帖子:http://www.java-forums.org/new-java/26110-joptionpane-when-called-inside-paintcomponent-method.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 2013-04-10
      相关资源
      最近更新 更多