我需要在底部的栏中制作一个带有一些按钮的框架。我所有的按钮都显示带有颜色的图像,例如黑色、灰色、白色等。我有一个面板,可以使用我选择的颜色进行绘制。问题是我不知道如何制作一种方法来在我按下按钮时捕捉那种颜色。
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);
}
最佳答案
建议:
- 通过
btnTab[indBtn].setActionCommand(btnName[indBtn]);
设置按钮的actionCommand| - ButtonGroup 可以通过获取选择来告诉您选择了哪个 Button,如果进行了选择,则该选择将是 ButtonModel 对象,如果没有选择,则为 null。
- 通过调用其
getActionCommand()
从上面的 ButtonModel 中获取选定按钮的 actionCommand 字符串方法。 - 考虑使用
HashMap<String, Color>
将 actionCommand 字符串与其关联的颜色链接起来。
还有
- 不要通过 getGraphics 获取组件的 Grahpics。而是在 BufferedImage 中绘制,然后在 JComponent(或扩展 JComponent 的类,如 JPanel)的 paintComponent 方法中绘制 BufferedImage。
- 您可以通过调用 getGraphics() 从 BufferedImage 中获取 Graphics 对象,但请务必在使用完后删除 Graphics 对象。
- 在您的 MouseListener 中,通过更改类字段来更改对象的状态,然后调用重绘。
关于java - 从我的 JButtons 获取颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9386227/