我想将test2
添加到我的DFrametest
课程中,以便test2
的表格显示在我的窗口中。我得到一个空窗口,找不到错误。
public class test2 extends JPanel {
JTable tbl;
DefaultTableModel dt;
public test2(){
JLabel label = new JLabel("Course Lookup GUI");
this.add( label );
tbl = new JTable();
dt = new DefaultTableModel();
dt.addColumn("ID");
dt.addColumn("Name");
tbl.setModel(dt);
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lagerverwaltungwin", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT ArtNr, Beschreibung FROM artikel");
}catch(Exception e){
e.printStackTrace();
}
JScrollPane jp = new JScrollPane();
jp.getViewport().add(tbl);
add(jp);
}
}
这是我的Frameclass
,应该有test2
的表格:
public class DFrametest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DFrametest frame = new DFrametest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DFrametest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
test2 t = new test2();
this.add(t);
this.setVisible(true);
}
}
答案 0 :(得分:2)
永远不要使用null布局。也不要使用setBounds(100, 100, 450, 300);
使用pack();
像这样更改您的DFrametest
课程
contentPane.setLayout(new BorderLayout());
contentPane.add(t, BorderLayout.CENTER);
DFrametest
课程的完整代码:
public class DFrametest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DFrametest frame = new DFrametest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DFrametest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
test2 t = new test2();
contentPane.setLayout(new BorderLayout());
contentPane.add(t, BorderLayout.CENTER);
pack();
}
}
答案 1 :(得分:-1)
尝试使用setBounds()方法,因为您还没有提到任何布局(setLayout为null)。 在将jpanel添加到jframe
之前添加setBounds方法setBounds(x-axis,y-axis,width,height);
EX: -
setBounds(10,20,200,400);
注意: