简体   繁体   English

从JOptionPane向面板添加字符串

[英]Adding a string to a panel from a JOptionPane

I'm working on a program that allows a user to enter a message. 我正在开发一个允许用户输入消息的程序。 When the user presses on the "message" menu item located in my frame, a JOptionPane input dialog box pops up prompting them to enter a string. 当用户按下位于我框架中的“消息”菜单项时,会弹出一个JOptionPane输入对话框,提示他们输入字符串。 The problem is that I have to now obtain that string and stick it into my panel class. 问题是我现在必须获取该字符串并将其粘贴到面板类中。 In addition I also allow the user to select a shape and color from a different dialog box when they press on another menu item also located in my frame. 另外,当用户按下也位于我框架中的另一个菜单项时,我还允许用户从其他对话框中选择形状和颜色。 The string has to be on top of the shape I've drawn. 字符串必须位于我绘制的形状之上。 I've tried draw string but it's not functioning properly. 我已经尝试过绘制字符串,但是它无法正常运行。 Here is my code which is not working. 这是我的代码不起作用。 I just want the string to draw on my panel when I hit OK on the JOptionPane . 我只希望在JOptionPane上单击OK时在面板上绘制字符串。 How would I do that? 我该怎么办?

In my frame 在我的框架中

private void messageItemActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    String message = JOptionPane.showInputDialog("Enter your string");

    // my panel
    drawP.setMessage(message);

}

in my Panel 在我的面板中

public void setMessage(String s) {
    message = s;
}

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

    // the user can select two different shapes this is
    // a boolean
    if (shape == true) {
        g.setColor(shapeColor);
        g.fillRect(x, y, 40, 40);
        g.drawString(message, x, y);

    } else {
        g.setColor(shapeColor);
        g.fillOval(x, y, 40, 40);
        g.drawString(message, x, y);
    }
}

Have you call repaint() after you set the message? 设置消息后,您是否调用过repaint() I tried before, repaint JFrame doesn't seems to works, but repaint JPanel works. 我之前尝试过,重新绘制JFrame似乎无效,但是重新绘制JPanel即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM