下面是一个有用的Java代码,我不明白。 我已经超出了程序调用getPreferredsize()和paintComponent()方法的时间。我发现每次调整DialogWindow时,它都会调用getPreferredsize-method()和两次paintcomponent-method()。
为什么?
package examples;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class Bsp {
public static void main(String[] args) {
JFrame frame = new MyFrame();
}
}
class MyFrame extends JFrame {
JPanel panel=new JPanel(new GridBagLayout());
private class MyLine extends JLabel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(5));
System.out.println("PaintComponent: "+getWidth()+" "+getHeight());
g2d.drawLine(0, panel.getHeight()/2, panel.getWidth(), panel.getHeight()/2);
g2d.dispose();
}
@Override
public Dimension getPreferredSize() {
System.out.println("PreferredSize: "+panel.getWidth()+" "+panel.getHeight());
return new Dimension(panel.getWidth(),panel.getHeight());
}
}
public MyFrame() {
JLabel label=new MyLine();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 1));
panel.add(label);
add(new JButton("A"));
add(new JButton("B"));
add(panel);
pack();
centeringWindow();
setVisible(true);
}
public void borderingJPanel(JComponent panel, String jPanelname,
String fontStyle) {
Font font = new Font(fontStyle, Font.BOLD + Font.ITALIC, 12);
if (jPanelname != null) {
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY,
Color.WHITE), jPanelname,
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION, font));
} else if (jPanelname == null || fontStyle == null) {
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY,
Color.WHITE)));
}
panel.setOpaque(false);
}
public void centeringWindow() {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x;
int y;
x = (int) (dimension.getWidth() - getWidth()) / 2;
y = (int) (dimension.getHeight() - getHeight()) / 2;
setLocation(x, y);
}
public BufferedImage getBufferedImage(){
BufferedImage buffImage=null;
try {
buffImage=ImageIO.read(MyFrame.class.getClassLoader().getResourceAsStream("examples/rightAnswerSign.png"));
} catch (IOException e) {
e.printStackTrace();
}
return buffImage;
}
}