색이 확인란에 해당하는 채워진 사각형을 그리려고합니다. 사각형은 임의로 크기를 정하고 JPanel
에 놓아야합니다. 지금까지 임의의 크기와 임의의 위치로 JPanel
에 그릴 직사각형을 가져 왔지만 체크 보스를 선택하면 직사각형을 그리는 데 문제가 있습니다. 내 ActionListener
코드는 내 프로젝트를 실행할 목적이 없으며 다른 것들을 시도했지만 문제가 있습니다. 대신 새로운 JComponent
각 시간을 만들려고 노력의JCheckBox를 클릭 할 때마다 사각형을 그리는 방법은 무엇입니까?
package colorViewerCheck;
public class ColorViewerCheckFrame extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
private JPanel colorPanel;
private JCheckBox redCheckBox;
private JCheckBox greenCheckBox;
private JCheckBox blueCheckBox;
public ColorViewerCheckFrame()
{
createColorPanel();
createControlPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createControlPanel()
{
class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (redCheckBox.isSelected()) {createColorPanel();}
if (greenCheckBox.isSelected()) {createColorPanel();}
if (blueCheckBox.isSelected()) {createColorPanel();}
}
}
ActionListener listener = new ColorListener();
redCheckBox = new JCheckBox("Red");
greenCheckBox = new JCheckBox("Green");
blueCheckBox = new JCheckBox("Blue");
redCheckBox.setSelected(true);
JPanel controlPanel = new JPanel();
controlPanel.add(redCheckBox);
controlPanel.add(greenCheckBox);
controlPanel.add(blueCheckBox);
redCheckBox.addActionListener(listener);
greenCheckBox.addActionListener(listener);
blueCheckBox.addActionListener(listener);
add(controlPanel, BorderLayout.SOUTH);
}
public void createColorPanel()
{
class RectangleComponent extends JComponent
{
private int x;
private int y;
private int width;
private int height;
private Random rand;
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
rand = new Random();
x = rand.nextInt(250);
y = rand.nextInt(350);
width = rand.nextInt(50);
height = rand.nextInt(50);
Rectangle rect = new Rectangle(x, y, width, height);
g2.setColor(getColor());
g2.fill(rect);
g2.draw(rect);
}
}
colorPanel = new JPanel(new GridLayout());
RectangleComponent rect = new RectangleComponent();
colorPanel.add(rect);
add(colorPanel, BorderLayout.CENTER);
colorPanel.setVisible(true);
}
public Color getColor()
{
Color color = null;
if (redCheckBox.isSelected()) {color = Color.RED;}
else if (greenCheckBox.isSelected()) {color = Color.GREEN;}
else if (blueCheckBox.isSelected()) {color = Color.blue;}
return color;
}
}
을은 "사각형"을 생성하고, 예를 들어, 도면 용기에 "추가"할 적어도 사용자를 위해서) '새로운 임의의 사각형 추가'를 위해'JCheckBox' 대신에'JButton'을 사용합니다. 확인란을 두 번 클릭하면 첫 번째 클릭에서 사각형이 표시되고 두 번째 클릭에서 사각형이 사라질 것으로 예상됩니다. –