[英]Buttons not visible until mouseover
我創建了一個框架和面板(用於Graphics
)並向面板添加了按鈕。 但是,當我運行我的程序時,按鈕是不可見的,直到我 hover 超過它們。 也許圖形方法有問題。
問題如何解決?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main{
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(600,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
Panel panel = new Panel();
f.add(panel);
f.setVisible(true);
}
}
class Panel extends JPanel implements ActionListener{
int[] x = {200,400,300,200};
int[] y = {100,100,200,100};
JButton fillRed;
JButton fillBlack;
JButton cancel;
Panel(){
this.setLayout(null);
fillRed = new JButton("Red");
fillRed.setBounds(50, 400, 100, 50);
fillRed.addActionListener(this);
this.add(fillRed);
fillBlack = new JButton("Black");
fillBlack.setBounds(250, 400, 100, 50);
fillBlack.addActionListener(this);
this.add(fillBlack);
cancel = new JButton("Cancel");
cancel.setBounds(450,400,100,50);
cancel.addActionListener(this);
this.add(cancel);
}
public void paint(Graphics g) {
super.paintComponent(g);
g.drawPolygon(x,y,4);
}
public void fillRed(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillPolygon(x,y,4);
}
public void fillBlack(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillPolygon(x,y,4);
}
public void cancel(Graphics g) {
super.paintComponent(g);
g.drawPolygon(x,y,4);
repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==fillRed) {
fillRed(getGraphics());
}
if(e.getSource()==fillBlack) {
fillBlack(getGraphics());
}
if(e.getSource()==cancel) {
cancel(getGraphics());
}
}
}
你的繪畫代碼大多是錯誤的。 例如:
public void paint(Graphics g) {
super.paintComponent(g);
g.drawPolygon(x,y,4);
}
如果你需要覆蓋 paint() 那么第一條語句應該是 super.paint(g)。
但是,您不應該覆蓋油漆。 對於自定義繪畫,您覆蓋paintComponent(...)
然后調用super.paintComponent(g)
。 閱讀有關自定義繪畫的 Swing 教程,了解更多信息和工作示例。
public void fillBlack(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillPolygon(x,y,4);
}
永遠不要直接調用 paintComponent(...) 。 如果您需要更改組件的屬性,則調用 repaint() 並且 Swing 將調用繪畫方法。
if(e.getSource()==fillRed) {
fillRed(getGraphics());
}
不要在 Swing 組件上調用 getGraphics()。 繪畫是通過設置 class 的屬性完成的,然后調用 repaint()。 如果您需要繪制多個對象,那么您需要跟蹤要繪制的每個 object,然后在繪制方法中每隔 object 繪制一次。查看自定義繪制方法以了解如何完成此操作的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.