[英]How to combine paintComponent(Graphics g) with MouseListener and MouseMotionListener
因此,我試圖結合使用paintComponent()以及使用MouseListener和MouseActionListener,但是我在運行它時遇到很多錯誤,但是我不希望它起作用。 具體來說,在此代碼中,我希望程序在您按下,拖動和釋放按鈕時,先獲取印刷機的坐標,然后獲得釋放的坐標,然后測量形狀的大小,並繪制指定的形狀通過JComboBox。 我在JFrame底部還有一個帶有按鈕的顏色選擇器。 我想知道如何在不自動運行的情況下運行paintComponent()方法,因此我可以在繪制之前給它指定規格,並按需繪制它。 另外,我想知道是否還有另一種方法可以做到這一點,而我如何實現它是完全錯誤的。 我希望解釋不要太混亂:)。 任何幫助都很好,謝謝!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings({"unchecked", "rawtypes"})
public class GraphicGUI extends JPanel implements ActionListener {
HandlerClass handler = new HandlerClass();
public int x1, x2, y1, y2, width, height;
public String event;
public JButton colorChooserButton;
public Color color = (Color.WHITE);
public JComboBox shapeBox;
public JLabel eventLabel;
public GraphicGUI(){
shapeBox = new JComboBox();
eventLabel = new JLabel();
colorChooserButton = new JButton("Choose a color");
colorChooserButton.addActionListener(this);
shapeBox.addItem("Oval");
shapeBox.addItem("Rectangle");
shapeBox.addItem("Line");
super.addMouseListener(handler);
super.addMouseMotionListener(handler);
}
public void actionPerformed(ActionEvent arg0){
if(arg0.getSource().equals(colorChooserButton)){
color = JColorChooser.showDialog(null, "Pick Your Color", color);
if(color==null){
color = (Color.BLACK);
}
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.white);
if(shapeBox.getSelectedItem() == "Oval")
if(event.equals("released")){
width = x1-x2;
height = y1-y2;
g.setColor(color);
g.fillOval(x1, y1, width, height);
}
}
private class HandlerClass implements MouseListener, MouseMotionListener{
//Mouse Events
public void mouseClicked(MouseEvent arg0){
event = "click";
}
public void mousePressed(MouseEvent arg0){
event = "pressed";
x1 = arg0.getX();
y1 = arg0.getY();
eventLabel.setText(String.format("Mouse pressed at %d, %d", x1, y1));
}
public void mouseReleased(MouseEvent arg0){
event = "released";
x2 = arg0.getX();
y2 = arg0.getY();
eventLabel.setText(String.format("Mouse released at %d, %d", x2, y2));
}
public void mouseEntered(MouseEvent arg0){
}
public void mouseExited(MouseEvent arg0){
}
//Mouse Motion Events
public void mouseDragged(MouseEvent arg0){
}
public void mouseMoved(MouseEvent arg0){
}
}
}
您應該開始繪制形狀。
public void paintComponent(Graphics g){
//Draw the oval
g.setColor(color);
g.fillOval(x1, y1, width, height);
}
public void mouseReleased(MouseEvent arg0){
event = "released";
x2 = arg0.getX();
y2 = arg0.getY();
if( x2 > x1 ) {
width = x2-x1;
} else {
width = x1-x2;
}
if( y2 > y1 ) {
height = y2-y1;
} else {
height = y1-y2;
}
eventLabel.setText(String.format("Mouse released at %d, %d", x2, y2));
}
然后(如果您想添加更多形狀),您需要一種添加形狀(duh)的方法,這樣您便可以獲得一個形狀列表並在該列表中進行迭代。
您確實應該(必須)初始化所有變量。
詢問是否需要更多詳細信息。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.