从我的评论中获取理论:-)
在我的评论中添加更多要点:
- 对于您扩展的任何内容,而不是
setSize()
在JFrame
, 而不是覆盖getPreferredSize()
方法上使用。JComponent/JPanel
现在只需调用pack()
,JFrame
来计算它自己的大小。
- 请阅读Swing 中的并发性
这是我所说的工作示例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JPanel {
private JButton button;
private String message;
private ActionListener buttonAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
message = input();
repaint();
}
};
public Main() {
message = "Nothing to display yet...";
}
private void displayGUI() {
JFrame frame = new JFrame("Painting Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
button = new JButton("Get Message");
button.addActionListener(buttonAction);
contentPane.add(this, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
@Override
public Dimension getPreferredSize() {
return (new Dimension(200, 200));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(message, 50, 50);
}
public String input() {
String x = ((String)JOptionPane.showInputDialog (
null, "Enter a string", "Test Project",
JOptionPane.QUESTION_MESSAGE,
null, null, null));
return x;
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new Main().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
编辑 1:
如果你不喜欢使用JButton
for 询问输入,你可以在你绘图的地方添加一个MouseListener
,JPanel
如下例所示:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JPanel {
private String message;
private int x;
private int y;
private MouseAdapter mouseAction = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
message = input();
x = me.getX();
y = me.getY();
repaint();
}
};
public Main() {
message = "Nothing to display yet...";
x = y = 0;
}
private void displayGUI() {
JFrame frame = new JFrame("Painting Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
addMouseListener(mouseAction);
contentPane.add(this, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
@Override
public Dimension getPreferredSize() {
return (new Dimension(200, 200));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(message, x, y);
}
public String input() {
String x = ((String)JOptionPane.showInputDialog (
null, "Enter a string", "Test Project",
JOptionPane.QUESTION_MESSAGE,
null, null, null));
return x;
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new Main().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}