我正在构建一个在 JPanel 上绘制random (User input) rectangles
的程序。
问题1:
每当我在
JTextfield
中输入数字时,我需要点击两次 显示Rectangles
的JBUtton。
问题2:
当我在JTextField中输入一个新号码时,该号码不会被删除 显示矩形,但它显示我在之前键入的矩形。
代码:
private void init() {
final int FRAME_WIDHT = 800;
final int FRAME_HEIGHT = 1000;
int input = 3;
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDHT, FRAME_HEIGHT);
frame.setTitle("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
west = new JPanel();
west.setSize(500, 500);
west.setBorder(BorderFactory.createLineBorder(Color.black));
east = new JPanel();
east.setSize(300, 1000);
button = new JButton("Add squares");
field = new JTextField(10);
button.setSize(100, 50);
east.add(button);
east.add(field);
east.setBorder(BorderFactory.createLineBorder(Color.black));
button.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton1ActionPerformed(evt);
}
public void JButton1ActionPerformed(ActionEvent evt) {
int aantalRect = Integer.parseInt(field.getText());
MyDrawing draw = new MyDrawing(aantalRect);
west.add(draw);
draw.revalidate();
draw.repaint();
}
});
frame.add(west, BorderLayout.CENTER);
frame.add(east, BorderLayout.EAST);
frame.setResizable(true);
frame.setVisible(true);
}
public static void main(String[] a) {
P1027 form = new P1027();
}
}
class MyDrawing extends JPanel {
int input = 0;
public MyDrawing(int i) {
this.input = i;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Random r = new Random();
setPreferredSize(new Dimension(500, 1000));
for (int i = 0; i < input; i++) {
int x = r.nextInt(460);
int y = r.nextInt(960);
g.drawRect(x, y, 40, 40);
}
}
Can any one tell me how to fix that?
答案 0 :(得分:1)
问题1:您第一次看到MyDrawing
JPanel
上的正方形,因为您正在呼叫setPreferredSize(...)
方法,当你真的应该覆盖this answer所解释的getPreferredSize()
方法时。也可能可能它们是在屏幕外绘制的。您将MyDrawing
的首选高度设置为1000
,这不适合my laptop's screen(绿线是MyDrawing
的边框)。
要解决问题1,请覆盖该方法并根据需要降低首选高度:
class MyDrawing extends JPanel {
... //Constructor
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500); //Changed from 1000 to 500
}
... //paintComponent(...)
//If you change 1000 to 500, don't forget to change 960 to 460 too
}
问题2:您之前看到的是您在JTextField
中输入的矩形数量,原因是:
MyDrawing
删除之前添加的west
。revalidate()
上呼叫repaint()
和draw
,而应在其父组件west
上调用它。要解决问题2,请从MyDrawing
移除旧的west
,添加新的revalidate()
,然后拨打repaint()
和...
public void JButton1ActionPerformed(ActionEvent evt) {
west.removeAll(); //If the old MyDrawing is the only thing
//that has been added to west. Otherwise use
//remove(int index) or remove(Component comp)
west.add(draw);
west.revalidate();
west.repaint();
}
...
:
T
其他事项:
H
中的FRAME_WIDTH
和JButton1ActionPerformed(...)
。actionPerformed
中的代码放入实际的JFrame
方法。setSize(...)
west
,east
以及button
和that answer {{1}} {{1}} {{1}} {{1}}看起来完全相同前面提到的建议不要使用这些方法,所以请考虑删除它们。