好吧,所以基本上我試圖編寫一個GUI應用程序,在其主窗口繪製2個圓形和2個矩形。我試圖獲得它,以便每當用戶在圓形或矩形內單擊時,該特定的圓形或矩形將更改爲另一種隨機顏色。Java圖形,使用點擊事件改變圖形的顏色
目前,我已經知道MouseClick事件(屏幕上的任何位置)會導致所有圓或矩形將顏色更改爲相同的顏色。 這是我到目前爲止有:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Question2 {
public static void main(String[] args) {
SecondFrame f = new SecondFrame("Draw and Fill");
f.init();
}
}
class SecondFrame extends JFrame{
SecondFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints gbc = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setContentPane(mainPanel);
gbc.gridheight = 1;
mainPanel.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
Point mousePosition;
mousePosition = mainPanel.getMousePosition();
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
Random ran = new Random();
// Assumes max and min are non-negative.
int red = 0 + ran.nextInt(255 - 0 + 1);
int green = 0 + ran.nextInt(255 - 0 + 1);
int blue = 0 + ran.nextInt(255 - 0 + 1);
Color myColor = new Color(red,green,blue);
g.setColor(myColor);
g.fillOval(50,50,200,200);
g.fillOval(50, 255, 200, 200);
g.fillRect(255,50,200,200);
g.fillRect(255, 255, 200, 200);
}
}
如果你可以點我在這將是非常讚賞的正確方向。謝謝。
什麼用超'();''在ShapeItem'的構造? – cyberpirate92
@cyberPheonix它調用父類的構造函數。在這種情況下,這是由Java自動完成的,並且不需要顯式添加語句來調用父級的默認構造函數。它可能是由Eclipse的* Generate構造函數使用fields ... *選項自動生成的。 – tenorsax