我有作业要做,但没有足够的信息,我现在陷入困境......这是问题,我有三门课:
“ChoicePanel”扩展了 JPanel 并添加按钮以使用 JComboBox 选择颜色
public class ChoicePanel extends JPanel{ Draw dessin; public ChoicePanel(Draw df) { dessin = df; ... // couleurs final JComboBox<String> couleurs = new JComboBox<>(new String[] {"bleu", "jaune", "rouge"}); add(couleurs); } /** Know what color is selected */ private Color determineCouleur(int indice){ switch (indice) { case 0: return Color.BLUE; case 1: return Color.YELLOW; case 2: return Color.RED; default: return Color.BLACK; } } }
“绘制”扩展 JPanel 并存储所有轮廓并绘制它们
“Main”创建包含这些类的框架
我必须将 Draw 设置为 MouseMotionListener,但无法在 ChoixePanel 中选择颜色,因为 JComobox 是在构造函数中创建的,并且无法将其设置为字段。 那么如何从 Draw 中检查 ChoicePanel 的按钮值?
每个答案都会非常有帮助!
最佳答案
练习的目标可能是帮助您了解 scope and access在 java 。让我们重构一下看到的例子 here满足您的要求。
ChoicePanel
需要一种方法来更新Draw
面板的实例;您可以将引用作为参数传递给面板的构造函数或工厂方法,如下所示。public static JPanel create(Draw draw) {…}
在组合的 Action 监听器中设置
绘制
的颜色;如果更改不是 bound property,则可以选择调用draw.repaint()
例如背景颜色。Hue h = (Hue) colors.getSelectedItem(); draw.setBackground(h.getColor()); //draw.repaint();
由于
Draw
可能不包含任何组件,因此请重写getPreferredSize()
,如下所示 here及以下。-
I can't create a private class…
为了方便运行下面的示例,
ChoicePanel
和Draw
作为private static
成员包含在内。只需将每个文件移至其自己的文件中,无需 modifiers ,从Main
获取具有包私有(private)访问权限的独立类。JFrame f = new JFrame("Main"); Draw d = new Draw(); f.add(d, BorderLayout.CENTER); f.add(ChoicePanel.create(d), BorderLayout.SOUTH);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* @see https://stackoverflow.com/a/5663782/230513
*/
public class Main {
private static class ChoicePanel {
public static JPanel create(Draw draw) {
JPanel p = new JPanel();
final JComboBox colors = new JComboBox();
for (Hue h : Hue.values()) {
colors.addItem(h);
}
colors.addActionListener((ActionEvent e) -> {
Hue h = (Hue) colors.getSelectedItem();
draw.setBackground(h.getColor());
});
p.add(colors);
return p;
}
}
private static class Draw extends JPanel {
public Draw() {
this.setBackground(Hue.values()[0].getColor());
}
@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
}
public enum Hue {
Cyan(Color.cyan), Magenta(Color.magenta), Yellow(Color.yellow),
Red(Color.red), Green(Color.green), Blue(Color.blue);
private final Color color;
private Hue(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
}
private void display() {
JFrame f = new JFrame("Main");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Draw d = new Draw();
f.add(d, BorderLayout.CENTER);
f.add(ChoicePanel.create(d), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Main().display();
});
}
}
关于java - 绘制另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274788/