我打算做一个简单的程序,每个问题都有4个问题,两个替代方案。
我想在JFrame的侧面添加四个圆圈,如果用户通过点击右侧选择右侧,则第一个圆圈将为绿色,然后如果他/她将在第二个问题上回答错误,则第二个圆圈为黄色,等等。
如何在JLabel中添加这些圈子???
答案 0 :(得分:2)
嗯......我建议在问这样的问题之前先开始学习Swing和Graphics2D:)
无论如何,作为一个开始提示,我可以建议一点......
要在JLabel或其他某个swing组件上绘图,您可以使用paintComponent(Graphics g)
方法。在开始之前,请仔细阅读文档和教程;
Here is a short example which shows how to draw upon JPanel因此您可以将其作为第一步的基础
编辑:
好的,所以你有像
这样的代码 import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class ShapePanel extends JPanel
{
public void paintComponent (Graphics g)
{
super.paintComponent(g);
g.setColor(Color.green);
g.drawOval(0,0, 20, 20);
g.setColor(Color.yelow);
g.fillOval(0, 0, 15, 15);
}
}
...并且您想要更改另一个对象中的颜色。对于此任务,您可以创建某种可观察对象,如下所示
>未经过测试
/**
* @author user592704
*/
class ShapePanel extends JPanel
{
private Color[] colors;
private Vector<MyCircleColorActionListener> myCircleColorActionListeners=new Vector<MyCircleColorActionListener>();
public static final int OVAL_COLOR=0;
public static final int FILL_OVAL_COLOR=1;
@Override
public void paintComponent (Graphics g)
{
this.myPaint(g);
}
private void myPaint(Graphics g)
{
super.paintComponent(g);
g.setColor(this.getColor()[ShapePanel.OVAL_COLOR]);
g.drawOval(0,0, 20, 20);
g.setColor(this.getColor()[ShapePanel.FILL_OVAL_COLOR]);
g.fillOval(0, 0, 15, 15);
}
private Color[] getColor() {
return colors;
}
private void setColor(Color[] colors) {
this.colors = colors;
this.repaint();
this.invokeObserver();
}
private void invokeObserver()
{
for(MyCircleColorActionListener myCircleColorActionListener:this.myCircleColorActionListeners)
{
myCircleColorActionListener.onColorChanged();
}
}
public void addMyCircleColorActionListener(MyCircleColorActionListener myCircleColorActionListener){this.myCircleColorActionListeners.add(myCircleColorActionListener);}
private JPanel getPanel(){return this;}
}
public interface MyCircleColorActionListener
{
void onColorChanged();
}
/**
* Some another object
*/
class MyAnotherClass extends JPanel implements MyCircleColorActionListener
{
private ShapePanel shapePanel=new ShapePanel();
private JButton testButton=new JButton("set red");
MyAnotherClass()
{
this.setLayout(new FlowLayout());
testButton.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
Color [] colors=new Color[2];
colors[ShapePanel.OVAL_COLOR]=Color.green;
colors[ShapePanel.FILL_OVAL_COLOR]=Color.red;
getShapePanel().setColor(colors);
}
});
this.add(testButton);
this.shapePanel.addMyCircleColorActionListener(this);
}
private ShapePanel getShapePanel(){return this.shapePanel;}
public void onColorChanged() {
System.out.println("Color was changed");
}
}
我还没有测试过,但我想这个概念必须清楚。
但在您尝试将其集成到代码中之前,我建议您仔细阅读how use action listeners in Swing components以及如何使用Patterns like Observer ...
如果您有其他问题,请评论
报告是否有用