我试图将用paintComponent()方法构造的图像放在JFrame的其他对象下面。我无法使paintComponent()方法显示在我的框架/面板上。
我扩展了JPanel,在带有图形参数的paintComponent()中使用了super,并且我还尝试重写该方法,这些方法都是解决此问题的常用方法,但是它们都无济于事,所以我假设它是另一个错误。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LayoutPractice extends JPanel{
Color currentColor;
private int numClicks = 0;
public void changeColor(Color currentColor) {
if (currentColor.equals(Color.RED)) {
currentColor = Color.GREEN;
} else {
currentColor = Color.RED;
}
}
public LayoutPractice() {
this.currentColor = Color.RED;
JFrame frame = new JFrame();
frame.setTitle("Mario GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
JPanel panel = new JPanel();
JLabel counterText = new JLabel("Button Clicked 0 times");
JButton dialogButton = new JButton("Click Me");
JButton characterButton = new JButton("Change Character");
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent mv) {
numClicks++;
counterText.setText("Button Clicked " + numClicks + " times");
}
});
dialogButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JOptionPane.showMessageDialog(panel,
"You have clicked " + numClicks + " times",
"Clicker Counter",
JOptionPane.INFORMATION_MESSAGE);
}
});
dialogButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
changeColor(currentColor);
}
});
panel.add(counterText);
panel.add(dialogButton);
panel.add(characterButton);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = 600;
int height = 400;
int pxW = width/13;
int pxH = height/7;
//hat, red color
g.setColor(currentColor);
g.fillRect((3 * pxW), 0, (6 * pxW), pxH);
g.fillRect((2 * pxW), pxH, (10 * pxW), pxH);
//skin, tan color
g.setColor(new Color(255,186,170));
g.fillRect((2 *pxW), (3 * pxH), pxW, (2*pxH));
g.fillRect((5 *pxW), (2 *pxH), (5 *pxW), pxH);
g.fillRect((4 *pxW), (3*pxH), (8 *pxW), pxH);
g.fillRect((5 *pxW), (4*pxH), (8 *pxW), pxH);
g.fillRect((3 *pxW), (5*pxH), (5*pxW), pxH);
g.fillRect((3 *pxW), (6*pxH), (8*pxW), pxH);
//hair, brown color
g.setColor(new Color(153, 102, 17));
g.fillRect((2 *pxW), (2 * pxH), (3 * pxW), pxH);
g.fillRect(pxW, (3 * pxH), pxW , (3 * pxH));
g.fillRect((3*pxW), (3* pxH), pxW, (2 * pxH));
g.fillRect((2*pxW), (5 *pxH), pxW, pxH);
g.fillRect((4 *pxW), (4 * pxH), pxW, pxH);
//eyes, black color
g.setColor(Color.BLACK);
g.fillRect((8*pxW), (2 * pxH), pxW, (2 *pxH));
g.fillRect((9*pxW), (4 *pxH), pxW, pxH);
g.fillRect((8*pxW), (5 *pxH), (4 *pxW), pxH);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new LayoutPractice();
}
});
}
}