我目前正在 Eclipse 上开发一个应用程序,我需要的是按一个按钮,然后打开一个 JFrame,其中包含来自 JTable 上的 MySQL DB 的值。我最近在这里问了一个关于我在尝试使用绝对布局(空布局)显示列时遇到的错误的问题,我被告知最好使用布局。问题是我现有的表单上有多个按钮和内容,更改布局会隐藏一些功能,而我找不到解决方案。所以我想到了一些东西。由于 JTable 存在绝对布局问题,并且布局管理器无法帮助我处理多个按钮,因此我可以从现有表单(空布局)中删除 JTable 并保留按钮。因此,当用户在现有表单上按下 mySQL 应用程序的“按名称排序”或“添加控制台”按钮时,应该会弹出一个新的 JFrame 并显示正确的 JTable。有没有可能的方法来做到这一点?
JTable 创建过程:
package newWindow;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;
public class newWindow {
public static void main(String[] args) {
new newWindow();
}
public newWindow() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {}
try
{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=mySQL&password=7777");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
String[] cols = new String[columnCount];
int i;
for (i=1;i<= columnCount;i++)
{
cols[i-1] = md.getColumnName(i);
}
DefaultTableModel model = new DefaultTableModel(cols,0);
while (rs.next())
{
Object[] row = new Object[columnCount];
for (i = 1 ; i <= columnCount ; i++)
{
row[i-1] = rs.getObject(i);
}
model.addRow(row);
}
JFrame frame = new JFrame("Promitheas");
JTable table = new JTable(model);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout());
JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
conn.close();
stmt.close();
rs.close();
} catch (SQLException case1) { case1.printStackTrace();
} catch (Exception case2) { case2.printStackTrace();}
}
});
}
}
按名称按钮排序:
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=mySQL&password=7777");
String[] gender = { "ASC", "DESC"};
int response = JOptionPane.showOptionDialog(null,"Ascending or Descending Order?","Make a choice...",0,JOptionPane.INFORMATION_MESSAGE,null,gender,gender[0]);
stmtsortname = conn.createStatement();
String sql = null;
if (response == JOptionPane.YES_OPTION)
sql = "ASC";
if (response == JOptionPane.NO_OPTION)
sql = "DESC";
rssortname = stmtsortname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id ORDER BY consoles.name "+sql);
.
.
.
create an newJTable overwriting the old
.
.
} catch ...
最佳答案
创建一个类,将要传输的数据作为参数。 做你的魔法设置表格并设置可见 true 并用你的逻辑替换 blala
public class NewJFrame extends JFrame{
public NewJFrame(Data data){
blala
this.setVisible(true);
}
}
然后在按钮上你有 ActionListner 或类似的东西
new NewJFrame(data);
关于java - 单击按钮打开一个新的 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25157895/