[英]Draw line on main window in Java
I'm trying to draw line on main window without creation a new window as it is in most examples which I found.我试图在主 window 上画线,而不创建新的 window,因为它在我发现的大多数示例中都是如此。 I have created a new project in NetBeans 8.1, added new JPanel and put two buttons in Design mode.
我在 NetBeans 8.1 中创建了一个新项目,添加了新的 JPanel 并将两个按钮置于设计模式。 Something like this:
像这样的东西:
public class NewJPanel extends javax.swing.JPanel {
/**
* Creates new form NewJPanel
*/
public NewJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
. . . .
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
// End of variables declaration
}
I would like to draw the line (10,10,100,100) by pressing Buttom1 and clean it by pressing Bottom2.我想按 Button1 画线 (10,10,100,100),然后按 Bottom2 清理它。 I will so appreciate the simplest example.
我会很感激最简单的例子。 Thanks a lot!
非常感谢!
You can use the paint method to draw 2D graphics in JPanel, to achieve your functionality create a boolean variable drawLine and set it to true for button1 and false for button2 as follows:您可以使用 paint 方法在 JPanel 中绘制 2D 图形,以实现您的功能创建一个 boolean 变量 drawLine 并将其设置为 true 为 button1 和 false 为 button2 如下:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
drawLine = true;
repaint();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
drawLine = false;
repaint();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private boolean drawLine = false;
Now Override the paint method in your panel and add following code to display line and clear it out if drawLine is false:现在覆盖面板中的paint方法并添加以下代码以显示线条并在drawLine为false时将其清除:
@Override
public void paint(Graphics arg0) {
super.paint(arg0);
Graphics2D gd = (Graphics2D) arg0;
if(drawLine){
gd.setColor(Color.RED);
gd.drawLine(10, 10, 100, 100);
}else{
super.paint(arg0);
}
}
In this way, you can draw line by pressing button1 and clear it out with button2.这样,您可以通过按button1绘制线条并使用button2将其清除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.