我在使用JButtons增加/减少已设置的JTextField时遇到了问题。
我知道需要使用ActionListener,但我不确定如何设置它。而且我还需要为多个JButton设置此功能,这进一步增加了这个过程的复杂性。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class App1 extends JFrame implements ActionListener, MouseListener
{
JPanel upper, lower, jp1, jp2, jp3;
JButton jb1, jb2, jb3, jb4, jb5, jb6;
JLabel jl1, jl2, jl3;
JTextField jtf1, jtf2, jtf3;
int count = 128;
public static void main(String[] args) {
App1 a1 = new App1();
}
public App1() {
JFrame myFrame = new JFrame("Color Selector");
myFrame.setLocationRelativeTo(null);
myFrame.setSize(new Dimension(600,400));
GridLayout layout = new GridLayout(2,1);
myFrame.setLayout(layout);
JPanel upper = new JPanel();
upper.setBackground(Color.GRAY);
JPanel lower = new JPanel(); add(lower);
lower.setLayout(new BoxLayout(lower, BoxLayout.X_AXIS));
lower.setBackground(Color.GRAY);
JPanel jp1 = new JPanel(); lower.add(jp1);
JPanel jp2 = new JPanel(); lower.add(jp2);
JPanel jp3 = new JPanel(); lower.add(jp3);
lower.addMouseListener(this);
JLabel jl1 = new JLabel("Red"); jp1.add(jl1);
JLabel jl2 = new JLabel("Green"); jp2.add(jl2);
JLabel jl3 = new JLabel("Blue"); jp3.add(jl3);
jp1.setBackground(Color.RED);
jp2.setBackground(Color.GREEN);
jp3.setBackground(Color.BLUE);
JButton jb1 = new JButton("R-"); jp1.add(jb1);
JTextField jtf1 = new JTextField(6);jp1.add(jtf1);
jtf1.setText("128");
JButton jb2 = new JButton("R+"); jp1.add(jb2);
jb1.addActionListener(this);
jb2.addActionListener(this);
JButton jb3 = new JButton("G-"); jp2.add(jb3);
JTextField jtf2 = new JTextField(6);jp2.add(jtf2);
jtf2.setText("128");
JButton jb4 = new JButton("G+"); jp2.add(jb4);
jb3.addActionListener(this);
jb4.addActionListener(this);
JButton jb5 = new JButton("B-"); jp3.add(jb5);
JTextField jtf3 = new JTextField(6);jp3.add(jtf3);
jtf3.setText("128");
JButton jb6 = new JButton("B+"); jp3.add(jb6);
jb5.addActionListener(this);
jb6.addActionListener(this);
myFrame.add(upper);
myFrame.add(lower);
myFrame.setVisible(true);
}
private void start() {
// TODO Auto-generated method stub
}
private static String setEditable(String string) {
// TODO Auto-generated method stub
return null;
}
private static String setText(String string) {
// TODO Auto-generated method stub
return null;
}
private static void add(JPanel lower) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
private void rebuild() {
// TODO Auto-generated method stub
}
}
我希望JButton可以通过使用JButtons来增加/减少已设置为“128”的JTextField的值。
JSpinner
?它已经提供了上下按钮来增加值。阅读 Swing 教程中关于如何使用 Spinners的部分,以获取更多信息和工作示例。 - camickr