[英]Drawing an oval on JButton when clicked
我已經開始為我的Java類開發一個項目 - LAN gomoku /連續五個。 游戲板由填充有按鈕(JButton)的二維陣列表示。 使用事件處理程序(類clickHandler)我想在我單擊的按鈕上繪制一個橢圓(clickHandler對象的參數)。 我的下面的代碼沒有工作(我不知道如何擺脫變量g的空值)...我很感激任何建議。 非常感謝。
class clickHandler implements ActionListener {
JButton button;
Dimension size;
Graphics g;
public clickHandler(JButton button) {
this.button = button;
this.size = this.button.getPreferredSize();
}
@Override
public void actionPerformed(ActionEvent ae) {
this.g.setColor(Color.BLUE);
this.g.fillOval(this.button.getHorizontalAlignment(), this.button.getVerticalAlignment(), this.size.width, this.size.height);
this.button.paint(this.g);
this.button.setEnabled(false);
}
}
(在創建GUI的類中 - 游戲板上裝滿了按鈕 - 我通過這種方式為每個按鈕分配一個新的Action Listener - clickHandler實例):
gButton.addActionListener(new clickHandler(gButton));
你必須:
paintComponent(Graphics g)
方法。 重寫getPreferredSize()
方法,它將返回Dimension
對象,並通過提供一個合適的大小,幫助Layout Manager
將JButton
放置在Container/Component
。
在那里制作圈子代碼。
添加一個onClickListener,並在單擊的按鈕上設置一個標志,並調用它進行重繪。
關於Graphics
對象:最好將它保存在paintComponent
方法中,並且只在那里使用它。 它將永遠傳遞給重畫,如果你把它保存在其他時刻,可能會發生奇怪的事情(快樂的實驗:))。
一個小例子:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample
{
private MyButton customButton;
private void displayGUI()
{
JFrame frame = new JFrame("Custom Button Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
customButton = new MyButton();
customButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
MyButton.isClicked = true;
customButton.repaint();
}
});
frame.getContentPane().add(customButton, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ButtonExample().displayGUI();
}
});
}
}
class MyButton extends JButton
{
public static boolean isClicked = false;
public Dimension getPreferredSize()
{
return (new Dimension(100, 40));
}
public void paintComponent(Graphics g)
{
if (!isClicked)
super.paintComponent(g);
else
{
g.setColor(Color.BLUE);
g.fillOval(getHorizontalAlignment(), getVerticalAlignment(), getWidth(), getHeight());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.