我试图在主窗口上画线而不创建新窗口,因为在我发现的大多数示例中都是如此。我在NetBeans 8.1中创建了一个新项目,添加了新的JPanel并将两个按钮置于“设计”模式。像这样:
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
}
我想按Buttom1画线(10,10,100,100),按Bottom2画线。我将不胜感激最简单的例子。
非常感谢!
最佳答案
您可以使用paint方法在JPanel中绘制2D图形,为实现您的功能,请创建一个布尔变量drawLine并将其对button1设置为true,对button2设置为false,如下所示:
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;
现在,覆盖面板中的paint方法,并添加以下代码以显示line并在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);
}
}
这样,您可以通过按button1画线,并用button2清除它。