Question

i'm new to java swing and i'm building an application with menu and JPanels with BorderLayout. But the Panel won't show not even with the setSize as i red here. Here i add the Panel to the Frame with the Menu:

if (actionEvent.getActionCommand() == "Tarif Änderung") {
        guiFrame.revalidate();
        guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TarifTextForm tarifForm =new TarifTextForm();
        tarifForm.setVisible(true);

        guiFrame.getContentPane().add(tarifForm);

        //show the frame
        guiFrame.pack();    
        guiFrame.setPreferredSize(new Dimension(500, 500));
        guiFrame.setVisible(true);

Here i build the Panel with the Textfield.

        tarifnameLbl=new JLabel();
    tarifnameLbl.setText("Tarifname:");
    tarifnameFld=new JTextField();
    tarifnameFld.setText("Zum starten, bitte tippen");


    betragLbl=new JLabel();
    betragLbl.setText("Betrag:");
    betragFld=new JTextField();
    betragFld.setText("0,00");

    JPanel p = new JPanel(new BorderLayout());

    p.add(tarifnameLbl, BorderLayout.WEST);
    p.add(betragLbl, BorderLayout.WEST);    
    p.add(tarifnameFld, BorderLayout.EAST);
    p.add(betragFld, BorderLayout.EAST);

    JPanel btnPanel = new JPanel();
    JButton newBut =new JButton();
    newBut.setText("Erstellen");
    btnPanel.add(newBut);

    JButton delBut=new JButton();
    delBut.setText("Löschen");
    btnPanel.add(delBut);

    JButton chgBut=new JButton();
    chgBut.setText("Ändern");
    btnPanel.add(chgBut);

    p.add(btnPanel, BorderLayout.SOUTH);
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout(10,10));
    panel.setSize(500,500);
    panel.add(p, BorderLayout.CENTER);

I don't understand where the Problem is :( Please help. Thanks a lot!

Was it helpful?

Solution

Error here:

if (actionEvent.getActionCommand() == "Tarif Änderung") {

Don't use == to compare Strings but rather use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of

if (fu == "bar") {
  // do something
}

do,

if ("bar".equals(fu)) {
  // do something
}

or,

if ("bar".equalsIgnoreCase(fu)) {
  // do something
}

or for your program:

if ("Tarif Änderung".equals(actionEvent.getActionCommand())) {
   // ....
}

Note also that

  • you're calling setVisible(true) on components that don't need this.
  • You're calling setPreferredSize(...) on a GUI after calling pack() which won't work.
  • You should avoid setting sizes and preferred sizes at all if possible but instead let components size to their natural sizes.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top