我刚刚开始编写课程2,它与我们以前的入门课程相比有了很大的提升。我要制作一个有三个按钮“红色”,“蓝色”,“绿色”的程序,当我点击“红色”时,会出现一个红色正方形。当我点击另一个按钮时,会有更多的正方形,正方形的颜色取决于我按下的按钮。 我的问题是,当我按下“红色”时,我必须在红色方块出现之前按另一个按钮。所以实际上看起来我按下的按钮会连接到错误的动作。这很难描述,但就像“一举一动”一样。你能提供像我这样的新手任何帮助吗?我总共有树类:SquareIcon,CompositeIcon和带框架的测试器。 只需要查看我在这里粘贴的最后一个课程。
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
/**
* Made by Rasmus
* Version 13-11-2014.
*/
public class SquareIcon implements Icon{
private int size;
private Color color;
public SquareIcon(int size, Color color) {
this.size = size;
this.color = color;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rec = new Rectangle2D.Double(x, y, size, size);
g2.fill(rec);
g2.setColor(color);
}
public int getIconWidth() {
return size;
}
public int getIconHeight() {
return size;
}
}
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* Made by Rasmus
* Version 13-11-2014.
*/
public class CompositeIcon implements Icon {
private ArrayList<Icon> icons;
public CompositeIcon() {
icons = new ArrayList<Icon>();
}
public void paintIcon(Component c, Graphics g, int x, int y) {
for (Icon i : icons) {
i.paintIcon(c, g, x, y);
x += i.getIconWidth();
}
}
public int getIconWidth() {
int width = 0;
for (Icon i : icons) {
width += i.getIconWidth();
}
return width;
}
public int getIconHeight() {
int height = 0;
for (Icon i : icons) {
if (i.getIconHeight() > height) {
height = i.getIconHeight();
}
}
return height;
}
public void addIcon(Icon i) {
icons.add(i);
}
}
最后一次:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Made by Rasmus
* Version 13-11-2014.
*/
public class FrameTest implements ActionListener {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
JButton redButton = new JButton("Rød");
JButton greenButton = new JButton("Grøn");
JButton blueButton = new JButton("Blå");
frame.add(redButton);
frame.add(greenButton);
frame.add(blueButton);
final CompositeIcon ci = new CompositeIcon();
final SquareIcon red = new SquareIcon(50, Color.RED);
final SquareIcon green = new SquareIcon(50, Color.GREEN);
final SquareIcon blue = new SquareIcon(50, Color.BLUE);
JLabel squareLabel = new JLabel(ci);
frame.add(squareLabel);
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ci.addIcon(red);
frame.pack();
frame.repaint();
}
});
greenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ci.addIcon(green);
frame.pack();
frame.repaint();
}
});
blueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ci.addIcon(blue);
frame.pack();
frame.repaint();
}
});
frame.setSize(250, 75);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
}
}
答案 0 :(得分:0)
我建议两件事:
首先,我建议您删除最后执行的操作块。该块可能导致错误。
其次,如果没有导致错误,请尝试插入断点或打印语句以查看它何时进入执行动作循环,然后您可以从那里开始工作。