**当我尝试更改任何组件的位置时,例如Button
Label
TextField
形状的某些部分将变得不可见。当删除代码时,将位置设置为组件的位置(在本例中为TextField
)将变为正常形状。**
public class Line {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame Example");
frame.setSize(1366, 768);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);
JButton button=new JButton("Show lines");
frame.add(button);
button.setBounds(60, 400, 220, 30);
button.setVisible(true);
JTextField txtf=new JTextField();
frame.add(txtf);
txtf.setVisible(true);
txtf.setSize(50, 100);
button.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent me) {
button.setVisible(false);
Graphics2D grf= (Graphics2D) frame.getGraphics();
txtf.setVisible(false);
txtf.setText("APPLE");
txtf.setLocation(600, 600);
txtf.setVisible(true);
grf.fillOval(600, 600, 10, 10);
grf.fillOval(190, 600, 10, 10);
grf.fillOval(900, 650, 10, 10);
grf.fillOval(750, 160, 10, 10);
grf.fillOval(600, 400, 10, 10);
grf.fillOval(1139, 266, 10, 10);
grf.drawLine(1144, 271, 605, 405);
grf.drawLine(195, 605, 605, 405);
grf.drawLine(755, 165, 605, 405);
grf.drawLine(755, 165, 1144, 271);
grf.drawLine(905, 655, 1144, 271);
grf.drawLine(905, 655, 605, 405);
grf.drawLine(205, 205, 605, 405);
grf.drawLine(205, 205, 755, 165);
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
});
button.setVisible(true);
}
}
当我尝试更改诸如按钮标签TextFielt之类的任何计算机的位置时,我的形状的某些部分变得不可见
您自定义的绘画都是错误的。您不应该使用框架的getGraphics()方法来获取Graphics对象。一旦Swing确定需要重新绘制组件,使用此方法的任何绘制都将丢失。
每当您更改Swing组件的属性时,都会重新绘制该组件。因此,您将松散与上述Graphics对象关联的所有绘画。
相反,您应该重写paintComponent(...)
JPanel并将绘画逻辑添加到该方法。然后,将JPanel添加到框架。
阅读有关定制绘画的Swing教程中的部分,以获取更多信息和工作示例。下载示例并根据您的实际需求对其进行自定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句