我正在編程序。點擊按鈕。創建圖紙。並點擊另一個按鈕使其移動。我的編碼有什麼問題?用java - swing
但我有一個錯誤的開始。
1st。雖然我用超級& actionlistener它編譯得很好,但它根本不起作用。
2nd。我應該如何使用線程進行編碼? (這並不意味着教我整個代碼,在我搞砸所有事情之前,我需要一些建議。)
這是我的編碼。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Hello extends JComponent{
//This is main code to create GUI
public Hello(){
EventQueue.invokeLater(new Runnable() {
public void run(){
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
//set Frame & layout
JPanel south = new JPanel();
testpane center = new testpane();
JButton b1 = new JButton("Create");
b1.setBackground(Color.WHITE);
b1.setFont(new Font("Arial",Font.ITALIC,20));
south.add(b1);
//setting the first button to create Things. i'll create another for move
b1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//repaint(); -> this was my trial for not working
center.setoutput();
}
//create action listener and **Here is the place I have a trouble**
});
frame.getContentPane().add(south, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Robot");
frame.setSize(500,500);
frame.setVisible(true);
}
});
}
public class testpane extends JPanel{
testpane(){
}
public void setoutput(){
repaint();
}// this is the fuction to call repaint at Hello class
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.BLACK);
g2.fillRect(100,100,30,30);
g2.drawRect(100, 100,30, 30);
g2.dispose();
}//this is the Thing that I want to draw
}
public static void main(String[] args){
new Hello();
}
//main class.
}
你可以在究竟是什麼更清晰這是不工作/你需要知道? – Stultuske
ActionListener不在監聽。我想知道如何讓創建的對象移動。 –
就像當我點擊按鈕時。這個矩形不會在 –