Some Swing Components not showing on JFrame

為{幸葍}努か 提交于 2019-12-25 07:25:58

问题


I've got a serious problem. When I try to add 2 JRadioButtons and a JLabel on my JFrame, it doesn't work. They are not showing, but other elements do.

The funny thing is, that other components which I added before (also JLabels) are visible on the JFrame.

All swing components are added over a container 'panel' which is the content pane of the JFrame.

I'm using Java DK 7 u67.

Here's the code: (Scroll down to /*This code doesn't work */)

public class UDP_FileTransfer implements KeyListener, Runnable {

JFrame fenster;
Container panel;
JButton startBt, setPathBt;
JTextField portFeld, ipFeld, savePathFeld;
JLabel infoLbl, serverLbl, clientLbl;
JRadioButton server, client;

boolean typeIsServer = true;

int port = 4444;
long size = 0;

boolean serverStarted;

public static void main(String[] args){

    new UDP_FileTransfer();
}

public UDP_FileTransfer(){

    fenster = new JFrame();
    fenster.setLayout(null);
    fenster.addKeyListener(this);
    fenster.setTitle("UDP File Transfer - Server");
    fenster.setLocationRelativeTo(null);
    fenster.setResizable(false);
    fenster.setSize(400,150);

    panel = fenster.getContentPane();
    panel.setLayout(null);
    panel.addKeyListener(this);

    JLabel portLbl = new JLabel("Port: ");
    portLbl.setBounds(10,10, 50,20);
    panel.add(portLbl);

    ...
    ...
    ...

    infoLbl = new JLabel("Status: Starten Sie den Server zuerst!");
    infoLbl.setBounds(10, 70, 371,20);
    infoLbl.setBorder(new LineBorder(Color.black, 1));
    panel.add(infoLbl);

    /* This code doesn't work */

    JLabel typeLbl = new JLabel("Wählen Sie den Typ aus:");
    typeLbl.setBounds(10,125,200,20);
    panel.add(typeLbl);

    client = new JRadioButton("Client");
    client.setBounds(230,125,70,20);
    panel.add(client);

    client = new JRadioButton("Server");
    client.setBounds(320,125,70,20);
    panel.add(client);

    /* End of non-working code */

    fenster.setVisible(true);
    fenster.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

The GUI looks like this: Click me

The JRadioButtons client & server and the JLabel typeLbl should appear under the box with the border.

I hope one of you can help me ...


回答1:


Firstly, you should change your latter variable to server.

    client = new JRadioButton("Client");
    client.setBounds(230,125,70,20);
    panel.add(client);

    server = new JRadioButton("Server");
    server.setBounds(320,125,70,20);
    panel.add(server);

and change your frame size

frame.setSize(450, 175);


来源:https://stackoverflow.com/questions/36751366/some-swing-components-not-showing-on-jframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!