Frage

Recently I have been playing around with Java Swing and am trying to create a custom Minecraft server launcher. When I press the button labeled "properties", it is supposed to change to a new panel and did at one point. However, for some reason I am unable to see it no longer works. Can anyone please help?

package custommcserver;

import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;

class Window extends JFrame implements ActionListener , ItemListener
{
    JPanel mainPnl = new JPanel(new GridLayout(2,1));
    JPanel propPnl = new JPanel();
    JButton startBtn = new JButton("Start");
    JButton stopBtn = new JButton("Stop");
    JButton propBtn = new JButton("Properties");

    JCheckBox allowNether = new JCheckBox("Allow players to visit the Nether dimension");

    public Window()
    {
        super("Custom Minecraft Server Launcher") ;
        setSize(500,200) ; 
        setDefaultCloseOperation(EXIT_ON_CLOSE) ;
        add(mainPnl) ;
        mainPnl.add(startBtn);
        mainPnl.add(stopBtn);
        mainPnl.add(propBtn);
        stopBtn.setEnabled(false);
        startBtn.addActionListener(this);
        stopBtn.addActionListener(this);
        propBtn.addActionListener(this);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent event) 
    {

        if (event.getSource() == stopBtn)
        {
            stopBtn.setEnabled(false);
            startBtn.setEnabled(true);
        }

        if (event.getSource() == startBtn)
        {
            stopBtn.setEnabled(true);
            startBtn.setEnabled(false);


        if (event.getSource() == propBtn)
        {
            add(propPnl);
            mainPnl.setVisible(false);
            propPnl.setVisible(true);
            propPnl.add(allowNether);
        }

    }
}

    @Override
    public void itemStateChanged(ItemEvent event) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
War es hilfreich?

Lösung

2 issues:

  1. The line

    if (event.getSource() == propBtn) {

    is within the if statement check for startBtn so there is effectively no check for this button. Move this out of that if statement block.

  2. Call revalidate and repaint on the the JFrame


Side notes:

  • CardLayout provides the functionality of replacing a component with another. Read How to Use CardLayout
  • Use anonymous ActionListener class instances to avoid issue #1.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top