我正在测试在面板中放置组件的耗时。 作为测试示例,我将数百个组件放置到jPanel。我正在寻找一种更快捷的方式来放置它们。这是我的测试代码:
import java.awt.*;
import javax.swing.*;
public class MyPane {
JFrame Myframe;
JPanel Mypanel;
public void createUI()
{
Myframe = new JFrame("Test clicks");
Mypanel = new JPanel();
Myframe.setPreferredSize(new Dimension(600, 600));
Myframe.setMinimumSize(new Dimension(600, 600));
Myframe.add(Mypanel);
Myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Myframe.setVisible(true);
//ADD 100+1 LABELS
long start_time = System.nanoTime();//START TIME
for (int i=0; i<100 ; i++){
JLabel myLabel= new JLabel();
myLabel.setText("label"+ i);
Mypanel.add(myLabel);
}
long end_time = System.nanoTime(); //START TIME
double difference = (end_time - start_time)/1000000;
//ADD EXECUTION TIME LABEL
JLabel MyInfo= new JLabel();
MyInfo.setText("milliseconds:"+ difference);
MyInfo.setBackground(Color.yellow);
MyInfo.setOpaque(true);
Mypanel.add(MyInfo);
Myframe.pack();
}
public static void main(String[] args) {
MyPane overlapPane = new MyPane();
overlapPane.createUI();
}
}
在我的电脑中添加1000个Jlabels需要120毫秒。当然,执行时间会因硬件,Os等而有很大差异。
我的问题是:是否有更快的方法在面板中放置许多组件。例如,有没有办法将所有这些放在一起?那会有什么不同吗?
编辑:我想澄清的是,在我开发的任何现实世界的软件中,将1000个标签一个接一个地放在一起并不是我想要实现的,尽管我有权这样做。这只是一个例子,我知道在某些情况下可以有更有效的方法在屏幕上显示大量的文本信息。另外,我的问题不是一般的软件优化问题,而是关于测试这种特定算法的问题。
答案 0 :(得分:2)
这会在196纳秒内添加 1,000,000 个可查看对象。
就像我说的那样,这取决于背景,而且是一个非常随意的问题。
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
class ManyObjects {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
Vector<Integer> v = new Vector<Integer>();
long start = System.nanoTime();
for (int ii=0; ii<=1000000; ii++) {
v.add(ii);
}
long end = System.nanoTime();
int duration = (int)((end-start)/1000000);
v.add(duration);
JList<Integer> list = new JList<Integer>(v);
System.out.println("Duration in seconds: " + duration);
JOptionPane.showMessageDialog(null, new JScrollPane(list));
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}