如果我有很多 JPanel,我将如何选择只使用其中一个?我正在尝试在我的绘图面板上绘制随机圆圈,但这不起作用?我无法让我的代码从 textArea 读取我的号码并在右侧面板中的随机位置和随机大小处生成该数量的圆圈。
主要的
public class Circles {
public static void main(String[]args){
JFrame frame = new JFrame("Cicles HW9 Chris Houston");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CirclesPanel());
frame.pack();
frame.setVisible(true);
}
}
控制板
public class CirclesPanel extends JPanel implements ActionListener{
private JButton draw, clear;
private JTextArea textArea;
private JPanel panel, drawPanel, buttonPanel;
private int count;
public CirclesPanel(){
JButton draw = new JButton("Draw");
JButton clear = new JButton("Clear");
JTextArea textArea = new JTextArea(1,10);
textArea.setBorder(BorderFactory.createTitledBorder("Circles"));
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
setPreferredSize(new Dimension(620, 425));
JPanel drawPanel = new JPanel();
drawPanel.setPreferredSize(new Dimension(450,400));
drawPanel.setBackground(Color.BLACK);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(3,1));
add(panel);
add(buttonPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.EAST);
buttonPanel.add(textArea);
buttonPanel.add(draw);
buttonPanel.add(clear);
draw.addActionListener(this);
clear.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == draw){
String tempText = textArea.getText();
count = Integer.valueOf(tempText);
repaint();
}
}
public void paintComponent(Graphics g) {
Random generator = new Random();
int x, y, diameter;
for(int i = 0; i < count; i++){
x = generator.nextInt(90);
y = generator.nextInt(90);
diameter = generator.nextInt(30);
g.drawOval(x, y, diameter, diameter);
}
}
}