如何使此GUI上的按钮工作? [英] How do I make the buttons on this GUI work?
本文介绍了如何使此GUI上的按钮工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个GUI,当您单击一个按钮时会增加一个数字,当您单击另一个按钮时减少该数字。这是我的代码:
I'm trying to make a GUI that will increase a number when you click one button and decrease that number when you click another button. This is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PushCounter
{
static JTextField textArea;
static int count = 0;
public static void main(String[] args)
{
JFrame frame = new JFrame("PushCounter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton upButton = new JButton("Up");
JButton downButton = new JButton("Down");
JTextField textArea = new JTextField(15);
JLabel label = new JLabel("Count");
upButton.addActionListener(new upButtonListener());
downButton.addActionListener(new downButtonListener());
panel.add(label);
panel.add(textArea);
panel.add(downButton);
panel.add(upButton);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.pack();
}
private static class upButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
++count;
textArea.setText(Integer.toString(count));
}
}
private static class downButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
--count;
textArea.setText(Integer.toString(count));
}
}
}
它编译,但GUI本身没有不行。做错了吗?你会如何创造这样的东西以及为什么?
我尝试过:
我使内部类静态,以便修复无法对非静态字段进行静态引用错误。那就是让它编译。我现在不知道它有什么问题。
It compiles, but the GUI itself doesn't work. Do what's wrong with it? How would you create something like this and why?
What I have tried:
I made the inner classes static in order to fix a cannot make static reference to non-static field error. That was to make it compile. I have no idea what's wrong with it now.
推荐答案
Se 如何编写动作侦听器(Java™教程>使用JFC / Swing创建GUI>编写事件监听器) [ ^ ]。
这篇关于如何使此GUI上的按钮工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文