我正试图为正在编写的Java应用程序创建一个简单的swing GUI,但在JPanel上显示内容时遇到了一些问题,我想知道是否有人能指出我做错了什么?
我的Gui.java类中有以下代码:
package openDIS;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Gui extends JFrame{
public Gui(){
setTitle("DIS Filter");
setSize(1000, 500);
setLocation (10, 10);
setDefaultCloseOperation(EXIT_ON_CLOSE);
initGui();
}
/*public quitButton(){
initGui();
} */
private void initGui(){
//JFrame frame = new JFrame();
JPanel panel = new JPanel();
this.getContentPane().add(panel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("DIS Filter");
this.setSize(1000, 500);
panel.setLayout(null);
/*Add a JTextArea to display the output DIS information */
JTextArea displayOutput = new JTextArea();
panel.add(displayOutput);
//String data = EspduReceiver.espdu;
int n = EspduReceiver.entitySite.size();
for (int i = 0; i < n; i++){
EspduReceiver.receivePdu();
System.out.println(EspduReceiver.entitySite.get(i));
System.out.println(EspduReceiver.entityApplication.get(i));
System.out.println(EspduReceiver.entity.get(i));
displayOutput.append(EspduReceiver.entitySite.get(i).toString());
displayOutput.append(EspduReceiver.entityApplication.get(i).toString());
displayOutput.append(EspduReceiver.entity.get(i).toString());
}
JButton quitButton = new JButton("Quit");
panel.add(quitButton);
quitButton.setBounds(875, 400, 80, 30); /*Set the location of the button in the window, and its size */
quitButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
panel.add(quitButton);
//setTitle("Quit");
//setSize(60,30); /*This line was overwriting the previously set values for the size of the window */
setLocationRelativeTo(null);
panel.repaint();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){ /* I probably don't need a main method here- I have one in EspduReceiver.java */
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
Gui gui = new Gui();
gui.setVisible(true);
}
});
}
}
目前,当我运行该类时,会打开一个名为"DIS Filter"的窗口,右下角有一个"Quit"按钮,退出按钮功能正常。
然而,无论我尝试什么,我似乎都无法显示JTextArea。。。有人能指出我在这里做错了什么吗?
谢谢!
您仍然需要布局,请使用FlowLayout作为最简单的布局。此外,您还必须设置JTextArea大小。
panel.setLayout(new FlowLayout());
/* Add a JTextArea to display the output DIS information */
JTextArea displayOutput = new JTextArea(50, 50);
panel.add(displayOutput);
不要使用null
布局;给文本区域一个优选的大小,并且pack()
是封闭的Window
。
JTextArea displayOutput = new JTextArea(3, 16);
试试这个:
displayOutput.setRows(20);
displayOutput.setColumns(5);
displayOutput.setVisible(true);