我仍然不熟悉在Java中使用Swing和创建GUI。我正在编写一个简单的测试代码,在这个代码中,按钮的颜色在按下时会变成随机颜色。虽然它工作,但每次我按下按钮,它会最小化以前的窗口,并打开一个新的窗口,他们不断堆积。我怎样才能避免这种情况发生呢?发生这种情况是因为我在actionPerformed方法中创建了一个对象吗?我之所以在那里创建了一个对象,是为了将Swing类与我创建的单独的Action类链接起来,以便操作按钮变量。
因此,我的两个问题是:
任何帮助都是非常感谢的!
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class Swing extends JFrame{
private JFrame f;
private JLabel l;
private JButton b;
private JPanel p;
public Swing(){
test();
}
//*
public JFrame getJFrame(){
return f;
}
public JLabel getJLabel(){
return l;
}
public JButton getJButton(){
return b;
}
public JPanel getJPanel(){
return p;
}
//*
public void test(){
// Frame Setup
f = new JFrame("Frame");
f.setVisible(true);
f.setSize(500, 500);
f.setResizable(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
//
// Panel Setup
p = new JPanel();
p.setVisible(true);
//
// Other
b = new JButton("Button");
l = new JLabel("Label");
b.addActionListener(new Action());
//
// Additions
p.add(b);
p.add(l);
f.add(p); // ***
//
}
public static void main(String[] args){
Swing swing = new Swing();
swing.test();
}
}
final class Action implements ActionListener{
public void actionPerformed(ActionEvent e){
Swing swingObject = new Swing(); //
JButton button = swingObject.getJButton(); //
button.setBackground(randomColor());
}
public Color randomColor(){
Random rn = new Random();
ArrayList<Color> color = new ArrayList<Color>();
color.add(Color.BLUE);
color.add(Color.GREEN);
color.add(Color.RED);
color.add(Color.YELLOW);
color.add(Color.PINK);
color.add(Color.CYAN);
color.add(Color.ORANGE);
color.add(Color.MAGENTA);
int s = color.size();
int random = rn.nextInt(s);
return color.get(random);
}
}发布于 2014-08-09 21:32:07
从您的侦听器,您正在执行
Swing swingObject = new Swing();这完成了它应该做的事情:创建一个新的Swing JFrame。您不需要一个新的JFrame,所以不要调用它的构造函数。从侦听器中,只需获取触发事件的按钮,并更改其颜色:
JButton button = (JButton) e.getSource();
button.setBackground(randomColor());您还可以在创建侦听器时传递要修改的按钮:
class Action implements ActionListener{
private JButton buttonToUpdate;
public Action(JButton buttonToUpdate) {
this.buttonToUpdate = buttonToUpdate;
}
public void actionPerformed(ActionEvent e){
buttonToUpdate.setBackground(randomColor());
}
}并且,为了创建它:
b = new JButton("Button");
b.addActionListener(new Action(b)); https://stackoverflow.com/questions/25223219
复制相似问题