我需要使用底部栏中的某些按钮创建框架。我的所有按钮都显示一个带有颜色的图像,例如黑色,灰色,白色等。我有一个我可以用我选择的颜色绘制的面板。问题是,当我按下按钮时,我不知道如何制作捕捉该颜色的方法。从我的JButton中获取颜色
private JToolBar barreOutils;
//
private JToggleButton[] btnTab = new JToggleButton[9];
//
private String[] btnName = { "Couleur noire", "Couleur grise",
"Couleur blanche", "Couleur rouge", "Couleur orange",
"Couleur jaune", "Couleur verte", "Couleur cyan", "Couleur bleue" };
//
private String[] btnColor = { "dark.gif", "gray.gif", "white.gif",
"rouge.gif", "orange.gif", "yellow.gif", "vert.gif", "cyan.gif",
"blue.gif" };
String[] colorTab = { "Color.DARK", "Color.GRAY", "Color.WHITE",
"Color.RED", "Color.ORANGE", "Color.YELLOW", "Color.GREEN",
"Color.CYAN", "Color.BLUE" };
// buttonGroup
private ButtonGroup groupeCouleurs;
// Notre panneau principal
private JPanel panneau;
public Fenetre() {
// Organization
setTitle("Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setLocationRelativeTo(null);
// Organization
panneau = new JPanel();
panneau.setBackground(Color.white);
panneau.addMouseListener(new Dessiner());
panneau.addMouseMotionListener(new Dessiner());
getContentPane().add(panneau);
//
barreOutils = createToolbar();
getContentPane().add(barreOutils, BorderLayout.SOUTH);
}
private JToolBar createToolbar() {
JLabel couleur = new JLabel("Couleurs : ");
barreOutils = new JToolBar();
groupeCouleurs = new ButtonGroup();
barreOutils.add(couleur);
createButton(btnTab, btnName, btnColor);
return barreOutils;
}
private void createButton(JToggleButton[] btnTab, String[] btnName,
String[] btnColor) {
// TODO Auto-generated method stub
// add the buttons on the bar at the bottom
for (int indBtn = 0; indBtn < btnTab.length; indBtn++) {
btnTab[indBtn] = new JToggleButton(new ImageIcon(
Fenetre.class.getResource(btnColor[indBtn])));
btnTab[indBtn].setToolTipText(btnName[indBtn]);
groupeCouleurs.add(btnTab[indBtn]);
barreOutils.add(btnTab[indBtn]);
}
}
private class Dessiner extends MouseAdapter {
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
Graphics g = ((JComponent) e.getSource()).getGraphics();
g.setColor(**???????????????????????**);
g.drawOval(e.getX(), e.getY(), 1, 1);
}
这也可以工作 - 1+。或者另一种解决方案是使用一个将JToggleButton的actionCommand String与Color相匹配的HashMap。 –
2012-02-21 22:34:56