[英]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.