[英]Button not working when trying to draw a line
我是Java的新手,正在教自己並嘗試構建此程序。 當鼠標單擊時,它將創建點,但在按下按鈕時不會畫線。 (最終這條線將連接點,但我還不在那里。)首先,我只需要讓它在被推動並從那里開始工作時畫點東西即可。 我已經嘗試了多種方法,但無法正常工作。 這是我的代碼:
public void init()
{
LineDrawListener listener = new LineDrawListener ();
addMouseListener (listener);
Button lineGraph = new Button("Graph Line");
lineGraph.addActionListener (this);
add (lineGraph, BorderLayout.EAST);
setBackground (Color.yellow);
setSize (APPLET_WIDTH, APPLET_HEIGHT);
}
public void paint(Graphics g)
{
// draws dots on screen
g.setColor(Color.blue);
if (current != null)
{
xcoordinates.addElement (current.x);
ycoordinates.addElement (current.y);
count++;
g.fillOval (current.x-4, current.y-4, 10, 10);
repaint();
}
if (push == true)
{
g.drawLine (5, 5, 30 , 30);
repaint();
}
}
class LineDrawListener extends MouseAdapter
{
public void mouseClicked (MouseEvent event)
{
current = event.getPoint();
repaint();
}
}
public void actionPerformed (ActionEvent event)
{
Object action = event.getSource();
if(action==lineGraph)
{
push = true;
}
}
任何有關如何使按鈕正常工作的幫助將不勝感激。 提前致謝。
JApplet
這樣的頂級容器上繪畫 在JPanel
上繪畫,並重寫paintComponent
方法,然后調用super.paintComponet(g)
@Override protected void paintComponent(Graphic g){ super.paintComponent(g); ... }
不要從paint()
方法內部調用repaint()
。 在您的actionPerformed()
調用它
第三是你最可怕的問題
不要覆蓋paint()。 不要在繪畫方法中調用repaint(),這會導致無限循環。
請查看“ 自定義繪畫方法” ,以獲取執行自定義paintint的兩種常用方法的工作示例:
無法繪制線條的原因是repaint()
發布了重新繪制組件的請求。 您正在使用它,就像它以某種方式刷新視圖一樣。 您需要在代碼中更改三件事,全部在paint()
:
paint()
調用repaint()
paint()
paintComponent()
而不是paint()
以便在以后需要時繪制邊框。 paintComponent()
調用super.paintComponent()
為您進行一些初始化。 不要為這種簡單但好的做法做准備,但將來也可以。 代碼如下所示:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// draws dots on screen
g.setColor(Color.blue);
if (current != null)
{
xcoordinates.addElement (current.x);
ycoordinates.addElement (current.y);
count++;
g.fillOval (current.x-4, current.y-4, 10, 10);
}
if (push == true)
{
g.drawLine (5, 5, 30 , 30);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.