非常感谢你,但我需要 Listener 方法并现在解决它。但现在我无法看到按钮,直到我将鼠标悬停在它们上!我认为这只是一个小错误,但我无法弄清楚!现在我的代码如下...
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class PaintMain extends JFrame
{
JPanel colorPanel = new JPanel();
JPanel drawPanel = new JPanel();
JPanel selectPanel = new JPanel();
JButton[][] randomColors = new JButton[5][5];
Color selectedColor = Color.BLACK;
Random colorGenerator = new Random();
int curx = drawPanel.getX();
int cury = drawPanel.getY();
public PaintMain()
{
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
colorPanel.setLayout(new GridLayout(5,5));
drawPanel.setLayout(new BorderLayout());
drawPanel.setBackground(Color.WHITE);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
randomColors[i][j]=new JButton();
randomColors[i][j].setBackground(getRandomColor());
randomColors[i][j].addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if( e.getSource() instanceof JButton)
{
selectedColor=((JButton)e.getSource()).getBackground();
System.out.println(selectedColor);
}
}
});
colorPanel.add(randomColors[i][j]);
}
}
this.addMouseMotionListener(new MouseLsnr());
add(colorPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.CENTER);
setVisible(true);
pack();
}
public Color getRandomColor()
{
return new Color(colorGenerator.nextInt(256), colorGenerator.nextInt(256), colorGenerator.nextInt(256));
}
public static void main(String[] args)
{
new PaintMain();
}
public void paint(Graphics g)
{
//super.paint(g);
g.setColor(selectedColor);
g.drawRect(curx, cury, 2, 1);
}
class MouseLsnr implements MouseMotionListener
{
public void mouseDragged(MouseEvent arg0) {
System.out.println(arg0.getX()+":"+arg0.getY());
curx=arg0.getX();
cury=arg0.getY();
repaint();
}
public void mouseMoved(MouseEvent arg0)
{
}
}
}