这是一个简单的问题,也许我只是不明白我正在阅读的教程。但我已经坚持了一段时间了。我的程序很简单,除了“hello world”之外。我想做的是:当用户单击按钮时,“O”向右移动。很简单,但是我该把 repaint() 放在哪里呢?我需要添加一些东西。repaint();重新绘制屏幕还是单独绘制屏幕?嵌套类问题? T_T 这让我很痛苦,似乎没有人遇到这个我无法理解的问题。提前致谢。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GuiTest {
static int x = 20;
private static class moveTest extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("O", x, 30);
}
}
private static class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
x += 1;
}
}
public static void main(String[] args) {
moveTest displayPanel = new moveTest();
JButton okButton = new JButton("move");
ButtonHandler listener = new ButtonHandler();
okButton.addActionListener(listener);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
JFrame window = new JFrame("GUI Test");
window.setContentPane(content);
window.setSize(250, 100);
window.setLocation(100, 100);
window.setVisible(true);
}
}
最佳答案
考虑让您的 MoveTest
面板导出 Action
供 GuiTest
按钮使用。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GuiTest {
private static class MoveTest extends JPanel {
private int x = 20;
private int y = 20;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("<O>", x, y);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(256, 128);
}
public Action getAction() {
return new ButtonHandler("Move");
}
private class ButtonHandler extends AbstractAction {
public ButtonHandler(String name) {
super(name);
}
@Override
public void actionPerformed(ActionEvent e) {
x += 2;
y += 1;
repaint();
}
}
}
public static void main(String[] args) {
MoveTest displayPanel = new MoveTest();
JButton moveButton = new JButton(displayPanel.getAction());
JFrame window = new JFrame("GUI Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(displayPanel);
window.add(moveButton, BorderLayout.SOUTH);
window.pack();
window.setLocationByPlatform(true);
window.setVisible(true);
}
}
关于java - 最简单的 Gui 测试 Java 重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17512823/