以下是我的代碼如下。它在執行時繪製三角形。我想對它做一些改變。 更改爲在Click基礎上繪製2D圖形對象
執行時會有1個三角形。但如果我在三角形1內點擊,則會畫出其他三角形。否則不畫。
我試圖與變化做g2d.draw(triangle2);
但它有問題。它只是不顯示三角形,但將其繪製爲隱藏。
public class Triangle_shape extends JFrame implements ActionListener {
public static int x=0;
public static JButton btnSubmit = new JButton("Submit");
public static JButton change = new JButton("Change");
public Triangle_shape(){
}
public static void main(String[] args) {
TrianglePanel t= new TrianglePanel();
ClickListener cl= new ClickListener();
JFrame frame = new JFrame();
final int FRAME_WIDTH = 500;
final int FRAME_HEIGHT = 500;
btnSubmit.addActionListener(cl);
frame.setSize (FRAME_WIDTH, FRAME_HEIGHT);
frame.setLayout(new BorderLayout());
frame.add(new TrianglePanel(), BorderLayout.CENTER);
frame.add(btnSubmit, BorderLayout.PAGE_END);
frame.add(change, BorderLayout.LINE_END);
frame.pack();
frame.repaint();
frame.setTitle("A Test Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static class TrianglePanel extends JPanel implements MouseListener{
private Polygon triangle,triangle2;
public TrianglePanel(){
//Create triangle
System.out.println("From Draw "+x);
triangle = new Polygon();
triangle.addPoint(150, 200);
triangle.addPoint(100, 100);
triangle.addPoint(200, 100);
triangle2 = new Polygon();
triangle2.addPoint(200, 300);
triangle2.addPoint(200, 200);
triangle2.addPoint(300, 200);
//Add mouse Listener
addMouseListener(this);
//Set size to make sure that the whole triangle is shown
setPreferredSize(new Dimension(300, 300));
}
/** Draws the triangle as this frame's painting */
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
System.out.println("From Graphics "+x);
g2d.draw(triangle);
g2d.draw(triangle2);
}
//Required methods for MouseListener, though the only one you care about is click
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
/** Called whenever the mouse clicks. */
public void mouseClicked(MouseEvent e) {
x++;
Point p = e.getPoint();
if(triangle.contains(p) )
System.out.println("1");
else if (triangle2.contains(p))
{ System.out.println("2");
}
else
{
System.out.println("Trianglhhhhhhhhhhhhhhhhhhpoint");
x--;}
}
}
private static class ClickListener implements ActionListener {
private int clickCount = 0;
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSubmit) {
clickCount++;
if (clickCount == 1)
btnSubmit.setText("clicked!");
else
btnSubmit.setText("Inside Triangle " + x + " times!");
}
else {
//JOptionPane.showMessageDialog(MainClass.this, "You must click at least once!",
btnSubmit.setText("Error " + clickCount + " times!");
}
}
}
}
當你三角形內1點擊,那麼它應該吸取三角形2或1內一個新的? – robin
繪製2.此代碼僅適用於2個三角形。 其實我想畫每一個點擊,如果它在裏面。但直到現在。考慮點擊三角1和繪製第二。 –