这是一个简单的问题,也许我只是不理解我正在阅读的教程。但我已经坚持了一段时间。我的程序就像它从一个" hello world"那样简单。我想要做的是:当用户点击按钮时," O"向右移动。很简单,但我在哪里放repaint()?我需要添加something.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);
}
}
答案 0 :(得分:4)
请考虑让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);
}
}
答案 1 :(得分:2)
您需要一个组件来呼叫repaint()
。最简单的解决方案是像这样调用repaint()
:
((JComponent)e.getSource()).getTopLevelAncestor().repaint();
问题是您的ActionListener
被声明为静态成员类,因此它无法访问封闭类的非静态成员,因为它与封闭类的实例无关。通常我将所有GUI初始化代码放在我自己的JPanel
子类的构造函数中。我还为侦听器使用匿名内部类。只要它们不是静态的,您就可以轻松使用命名类。然后你可以在监听器方法中调用JPanel方法。