问题描述
当我只使用它工作的 JTable 时,它是可见的, Only JTable 但是当我添加 JScrollPane 时它是不可见的。 With JScrollPane
package Menu;
import Objects.Background;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Highscore extends JFrame {
public Highscore() {
setLayout(null);
setDefaultCloSEOperation(disPOSE_ON_CLOSE);
setBounds(250,100,1050,650);
this.setLayout(null);
Background background = new Background();
background.setBounds(0,650);
add(background);
background.setLayout(null);
JButton back = new JButton("BACK");
back.setBounds(800,550,30);
background.add(back);
String[][] info = new String[100][2];
String[] nevek=new String[100];
int[] pontok = new int[100];
int i=0;
// read the highscores
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("highscores.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
String[] parts = strCurrentLine.split("\\,");
String nev = parts[0];
String pont = parts[1];
nevek[i]=nev;
pontok[i]= Integer.parseInt(pont);
i++;
}
} catch (IOException e) {
e.printstacktrace();
} finally {
try {
if (objReader != null)
objReader.close();
} catch (IOException ex) {
ex.printstacktrace();
}
}//---bubble sort for the highscores
for (int j=0; j<i; j++)
{
for (int k=0; k<i; k++)
if(pontok[j]>pontok[k]) {
String seged2=nevek[j];
int seged=pontok[j];
pontok[j]=pontok[k];
nevek[j]=nevek[k];
pontok[k]=seged;
nevek[k]=seged2;
}
}
//--matrix for the JTable
for (int j=0; j<i; j++)
{
info[j][0]=nevek[j];
info[j][1]= String.valueOf(pontok[j]);
}
//initialize Jtable and JScrollPane
String[] columnNames={"Name","score"};
JTable scores = new JTable(info,columnNames);
scores.setBounds(325,325,190);
JScrollPane jScrollPane = new JScrollPane(scores);
background.add(jScrollPane);
back.addActionListener(e -> {
new MainMenu();
dispose();
});
setVisible(true);
}
}
这是我班级的完整代码。 我正在尝试使用带有 JScrollPane 的 JTable,我也在 JTable 和 JScrollPane 上尝试过 setVisible。 我认为问题可能是我将 JScrollPane 添加到 JPanel 而不是 JFrame,但我希望我的面板上有那个分数表。 在我的 JPanel(背景)中,我为背景绘制了一个图像,仅此而已。
大家有什么想法吗?
解决方法
您没有看到表格,因为您错误地使用了空布局。
不要使用空布局!!!
不要使用 setBounds(...)!!!
Swing 旨在与布局管理器一起使用。了解如何使用布局管理器。
你的基本代码应该是:
Background background = new Background().
background.setLayout( new BorderLayout() );
JButton button = new JButton(...);
background.add(button,BorderLayout.PAGE_START);
JTable table = new JTable(...);
background.add(new JScrollPane( table ),BorderLayout.CENTER);
add(background);
现在按钮和滚动面板将被添加到背景面板,背景面板将被添加到框架中。
阅读关于 Layout Managers 的 Swing 教程中的部分,了解更多信息和布局管理器的工作示例。
本教程还有一个关于 How to Use Tables
的部分。您也可以从那里下载工作演示代码来练习使用布局管理器。