簡単なプログラムを作成し、すべての質問に対して 4 つの質問と 2 つの選択肢を用意します。
JFrame の側面に 4 つの円を追加したいのですが、ユーザーが正しい代替をクリックして正しいと答えた場合、最初の円は緑色になり、2 番目の質問で間違って答えた場合、2 番目の円は黄色になります。 .
これらの円を JLabel に追加するにはどうすればよいですか???
ええと...そのような質問をする前に、SwingとGraphics2Dの学習を開始することをお勧めします:)
とにかく、最初のヒントとして、少しアドバイスできます...
メソッドを使用して、 JLabelまたはその他のスイング コンポーネントを描画できますpaintComponent(Graphics g)
。開始する前にドキュメントとチュートリアルをよく読んでください。
JPanel を使用する方法を示す短い例を次に示します。これにより、最初のステップの基礎として使用できます。
編集 :
OKなので、次のようなコードがあります
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");
}
}
まだテストしていませんが、概念は明確であると思います。
ただし、コードに統合する前に、Swing コンポーネントでアクション リスナーを使用する方法とObserver などのパターンを使用する方法を注意深く読むことをお勧めします。
追加の質問がある場合はコメントしてください
それが役に立ったかどうかを報告する