我有一个有4个选项卡的JTabbedPane。我想在选项卡使用、引用和从同一数据库检索时一个接一个地加载1个选项卡。这导致我的应用程序中出现“数据库被锁定”的问题。
提前感谢您的帮助和建议:)
这就是我创建JTabbedPane的方式
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBounds(0, 0, 450, 300);
tabbedPane.addTab("tab1", new class1UseDb());
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
tabbedPane.addTab("tab2", new class2UseDb());
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
tabbedPane.addTab("tab3", new class3UseDb());
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
tabbedPane.addTab("tab4", new class());
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
基于此示例,下面的sscce只需为每次单击Add按钮创建一个新面板并填写结果。在实际程序中,您可能希望使用SwingWorker
来管理延迟和资源。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import org.h2.jdbcx.JdbcDataSource;
/**
* @see https://stackoverflow.com/a/19860170/230513
* @see https://stackoverflow.com/a/15715096/230513
* @see https://stackoverflow.com/a/11949899/230513
*/
public class TabData {
private int n = 1;
private void display() {
JFrame f = new JFrame("TabData");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTabbedPane jtp = new JTabbedPane();
jtp.add(String.valueOf(n), createPane());
f.add(jtp, BorderLayout.CENTER);
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Add") {
@Override
public void actionPerformed(ActionEvent e) {
jtp.add(String.valueOf(++n), createPane());
jtp.setSelectedIndex(n - 1);
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JPanel createPane() {
JPanel p = new JPanel();
JLabel l = new JLabel();
p.add(new JLabel("Result: "));
p.add(l);
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:file:~/src/java/jdbc/test;IFEXISTS=TRUE");
ds.setUser("sa");
ds.setPassword("");
try {
Connection conn = ds.getConnection();
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT RAND() FROM DUAL");
rs.next();
l.setText(rs.getString(1));
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new TabData().display();
}
});
}
}