【发布时间】:2014-05-09 00:18:07
【问题描述】:
我正在尝试创建一个 java 程序,当用户单击 Frame 时,它将在 JFrame 上绘制一个形状。我已经到了将其设置为接受不同形状并识别点击的地步,但我无法弄清楚如何实现形状的绘制。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.JComponent;
public class StamperFrame extends JFrame {
private JButton circleButton, ovalButton, squareButton, rectButton;
private int buttonValue = 0;
public StamperFrame() {
setTitle("Shape Stamper");
setSize(500, 500);
//Setting up the buttons and positioning them.
JPanel buttonPanel = new JPanel();
circleButton = new JButton("Circle");
ovalButton = new JButton("Oval");
squareButton = new JButton("Square");
rectButton = new JButton("Rectangle");
buttonPanel.add(circleButton);
buttonPanel.add(ovalButton);
buttonPanel.add(squareButton);
buttonPanel.add(rectButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
//end button init
//Setting up button logic
circleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonValue = 1;
System.out.println(buttonValue);
}
});
ovalButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonValue = 2;
System.out.println(buttonValue);
}
});
squareButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonValue = 3;
System.out.println(buttonValue);
}
});
rectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonValue = 4;
System.out.println(buttonValue);
}
});
//end button click configuration
getContentPane().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (buttonValue == 1) {
System.out.println("Circle added at: " + e.getX() + "," + e.getY());
} else if (buttonValue == 2) {
System.out.println("Oval added at: " + e.getX() + "," + e.getY());
}else if (buttonValue == 3) {
System.out.println("Square added at: " + e.getX() + "," + e.getY());
}else if (buttonValue == 4) {
System.out.println("Rectangle added at: " + e.getX() + "," + e.getY());
}
}
});
}
}
我知道它需要以某种方式在我的鼠标事件中起作用,但我不知道如何。
我的框架目前看起来像这样:http://puu.sh/8ELaR/c7252286c0.jpg
任何建议将不胜感激。
【问题讨论】:
标签: java swing mouseevent actionlistener paintcomponent