Java添加后台后,为什么程序会变慢?
因此,如果我添加背景图片,然后多次单击按钮,我的程序将越来越慢。但如果我不添加背景图片,它不会变慢。谁能告诉我为什么?谢谢 以下是我的JFrame类:Java添加后台后,为什么程序会变慢?,java,swing,user-interface,Java,Swing,User Interface,因此,如果我添加背景图片,然后多次单击按钮,我的程序将越来越慢。但如果我不添加背景图片,它不会变慢。谁能告诉我为什么?谢谢 以下是我的JFrame类: public class test extends JFrame implements ActionListener { private Container contentPane; public test() throws FileNotFoundException { // set the position
public class test extends JFrame implements ActionListener {
private Container contentPane;
public test() throws FileNotFoundException {
// set the position of the GUI related with screen size
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
this.setBounds((int) width / 4, (int) height / 4, (int) width / 2, (int) height / 2);
//set background
ImageIcon img = new ImageIcon("background.jpeg");
// get the container
contentPane = this.getContentPane();
//contentPane.setLayout(new GridLayout(3, 1));
/*
*background panel
*/
JPanel backgroundPanel = new JPanel(){
{
this.setOpaque(false);
}
public void paintComponent(Graphics g) {
img.setImage(img.getImage().getScaledInstance(this.getWidth(), this.getHeight(), Image.SCALE_AREA_AVERAGING));
g.drawImage(img.getImage(), 0, 0, this);
super.paintComponent(g);
}
};
contentPane.add(backgroundPanel);
backgroundPanel.setLayout(new GridLayout(3, 1));
/*
* second area
*/
JPanel secondPanel = new JPanel();
secondPanel.setOpaque(false);
// display button
makeButton(secondPanel, "Display", this);
backgroundPanel.add(secondPanel);
}
private void makeButton(JPanel p, String name, ActionListener target) {
JButton b = new JButton(name);
b.setFont(new Font(null, Font.PLAIN, 20));
// add it to the specified JPanel and button group and make the JPanel listen
p.add(b);
b.addActionListener(target);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String command = e.getActionCommand();
// Load button
// Display button
if (command.equals("Display")) {
// check is there any document has been loaded
// pop-up window
JOptionPane.showMessageDialog(null, "Please load a document first!", "Error",JOptionPane.PLAIN_MESSAGE);
}
// show states button
}
}
以下是主要方法:
public class DocumentViewer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
JFrame frm = new test();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
在这里:
public void paintComponent(Graphics g) {
img.setImage(img.getImage().getScaledInstance(this.getWidth(), this.getHeight(), Image.SCALE_AREA_AVERAGING));
g.drawImage(img.getImage(), 0, 0, this);
super.paintComponent(g);
}
您正在一种绘画方法中进行资源匮乏的计算,这种方法极大地提高了用户感知的程序响应能力。不要这样做。缩放图像一次,并将其存储在变量中,然后仅在paintComponent方法中绘制图像
如果需要使用GUI调整图像的大小,则在ComponentListener中进行调整,而不是在绘制方法中进行调整