我創建了一個框架和面板(用于Graphics)并向面板添加按鈕。但是,當我運行我的程式按鈕時,直到我將滑鼠懸停在它們上面才可見。也許圖形方法有問題。
如何解決問題?
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());
}
}
}
uj5u.com熱心網友回復:
您的繪畫代碼大多是錯誤的。例如:
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()。繪畫是通過設定類的屬性完成的,然后呼叫 repaint()。如果您需要繪制多個物件,則需要跟蹤要繪制的每個物件,然后在繪制方法中繪制每個物件。查看自定義繪畫方法,例如如何做到這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/473176.html
