SWING - 绘制直线,编译时不会出现

时间:2012-11-02 18:19:39

标签: java swing jframe paintcomponent

我试图在JFrame窗口中用鼠标画线,当我尝试这样做时,它不起作用!请忽略菜单,我想稍后再做一些事情!我错过了什么!如果你能给我一些提示,我将不胜感激!

public class newGUI extends JFrame implements ActionListener, MouseMotionListener, MouseListener {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
Point point1;
Point point2;
Line2D line2d;

public static void main(String[] args){
    newGUI gui = new newGUI();
    gui.setVisible(true);
}

public newGUI()
{
    super("Menu Demonstration");
    setSize(WIDTH, HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenu colorMenu = new JMenu("Choose Colors");
    JMenuItem greenChoice = new JMenuItem("GREEN");
    greenChoice.addActionListener(this);
    colorMenu.add(greenChoice);
    JMenuItem redChoice = new JMenuItem("RED");
    colorMenu.add(redChoice);
    JMenuBar bar = new JMenuBar();
    bar.add(colorMenu);
    setJMenuBar(bar);
    addMouseListener(this);
    addMouseMotionListener(this);
}
@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseClicked(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub
    point1=arg0.getPoint();
}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseDragged(MouseEvent arg0) {
    // TODO Auto-generated method stub
    point2=arg0.getPoint();
    line2d=new Line2D.Double(point1, point2);
    repaint();

}

@Override
public void mouseMoved(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    if(point1!=null && point2!=null){
        g2d.setPaint(Color.RED);
        g2d.setStroke(new BasicStroke(1.5f));
        g2d.draw(line2d);
        repaint();
    }
}
}

1 个答案:

答案 0 :(得分:5)

  • 始终以大写字母NewGui
  • 开始上课
  • 使用Event Dispatch Thread创建和更改UI组件
  • 不要无限延长JFrame课程
  • 请勿致电setSize(..)而是致电JFrame#pack()实例
  • 上的JFrame
  • JFrame没有paintComponent(..),而是添加自定义JPanel并覆盖其paintComponent(..)getPreferredSize(..)
  • 别忘了在自定义super.paintComponent(..)
  • 中致电JPanel
  • 请勿在{{1​​}}内拨打repaint()(这会导致无限循环重新绘制超过需要的数量)
  • 如果可能(如果其他类没有使用),请使用匿名paintComponent(..) s / MouseListener s而不是使用MouseMotionListener代替MouseAdapter / {{1等等。

这是我做的一个例子(基本上是你提到修复的代码):

enter image description here

MouseListener