我正在通过一本书(肮脏的富客户端,而不是引用它)学习Java和Swing,我在Linux上尝试了以下简短的示例代码(Oracle JDK 8):
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class OvalComponent extends JComponent {
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.GRAY);
g.fillOval(0, 0, getWidth(), getHeight());
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Oval");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(200, 200);
f.add(new OvalComponent());
f.setVisible(true);
}
public static void main(String args[]) {
Runnable doCreateAndShowGUI = new Runnable() {
public void run() {
createAndShowGUI();
}
};
SwingUtilities.invokeLater(doCreateAndShowGUI);
}
}
当我运行这段代码时,我奇怪地在JFrame
边界上观察到以下“神器”:
拖动窗口时会保留此“工件”,但调整窗口时会消失。我想了解为什么我在Linux上有这种奇怪的行为。这是Linux固有的(在Windows 7上我没有观察到任何工件),为了修复这个“bug”应该/可以做些什么?
我还观察到只是在super.paintComponent(Graphics g);
方法的开头简单地调用paintComponent
解决了这个问题。但是,非常奇怪的是,书中的作者说,在这种特殊情况下,没有必要调用super.paintComponent()
。
我的主要问题是:为什么我在Java窗口上观察到这个黑色神器?
和Paul一样,我没有注意到右侧的神器,如上面的屏幕截图所示。话虽如此,很可能是因为没有调用超级方法。调用它将导致组件的背景被绘制。
以下是我建议在代码中实现的一些其他建议,在每个建议之前使用代码注释来讨论原因。
// A JPanel does some things automatically, so I prefer to use one
//public class OvalComponent extends JComponent {
public class OvalComponent extends JPanel {
// Use @Override notation!
@Override
public void paintComponent(Graphics g) {
// call the super method first..
super.paintComponent(g);
// this is better achieved with the call to super
//g.setColor(getBackground());
//g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.GRAY);
g.fillOval(0, 0, getWidth(), getHeight());
}
// suggest a size for the layout manager(s) to use..
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Oval");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// DON'T TRY TO GUESS WHAT SIZE THE FRAME SHOULD BE!
// f.setSize(200, 200);
f.add(new OvalComponent());
// Instead pack the top level container after components added
f.pack();
f.setVisible(true);
}
public static void main(String args[]) {
Runnable doCreateAndShowGUI = () -> {
createAndShowGUI();
};
SwingUtilities.invokeLater(doCreateAndShowGUI);
}
}