当我单击相应的按钮时,我希望 GUI 在我在方法 paintComponent
中编码的确切位置上绘制圆形/矩形。
但我就是不知道如何继续下去。我应该告诉 actionPerformed
做什么?尝试了几个小时来找出一种方法,但我只收到错误。
public class Kreise extends JFrame {
Kreise() {
setLayout(new GridLayout(2, 1));
JLabel label = new JLabel("Draw Circ / Rect here: ");
label.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel jp1 = new JPanel();
jp1.setBackground(Color.LIGHT_GRAY);;
jp1.add(label);
JPanel jp2 = new JPanel(new FlowLayout());
JButton circ = new JButton("Circle");
JButton rect = new JButton("Rectangle");
circ.addActionListener(new KRListener(true));
rect.addActionListener(new KRListener(false));
jp2.add(circ);
jp2.add(rect);
MyPanel obj = new MyPanel();
jp1.add(obj);
add(jp1);
add(jp2);
setSize(400, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public class MyPanel extends JPanel {
public boolean circleZ = true;
public void paintComponent(Graphics g) {
if (circleZ = true) {
super.paintComponent(g);
g.drawOval(150, 50, 50, 50);
} else if (circleZ = false) {
super.paintComponent(g);
g.drawRect(150, 50, 50, 50);
}
}
}
public class KRListener implements ActionListener {
boolean b;
KRListener(boolean b) {
this.b = b;
}
public void actionPerformed(ActionEvent e) {
?
}
}
public static void main(String[] args) {
new Kreise();
}
}
最佳答案
假设我清楚地理解这个问题(您希望在矩形或圆形之间切换),在 ActionListener
实现中您需要:
- 切换适当的 boolean 值
- 在执行绘制的
JPanel
实例上调用repaint
完成这些步骤的一种方法是使用单个切换 JButton
,并将用于绘图的 JPanel
实例传递给 ActionListener
> 实现,可用于完成上述两个步骤:
public class KRListener implements ActionListener {
private MyPanel panel;
KRListener(MyPanel panel) {
this.panel = panel;
}
@Override
public void actionPerformed(ActionEvent e) {
panel.circleZ = !panel.circleZ;
panel.repaint();
}
}
当你画画时:
if ( circleZ ){
g.drawOval(150, 50, 50, 50);
}else{
g.drawRect(150, 50, 50, 50);
}
关于java - ActionListener 在单独的面板上绘制形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39478827/