Using CardLayout for multiple JPanels and nothing

2020-05-01 14:25发布

问题:

I'm making a simple (and bogus) computer power consumption calculator. I'm using a card layout to put multiple panels in but when I run it, there's just a small window not displaying anything. Here's my long code, I put it all in one class.

package my.Project;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DecimalFormat;
import javax.swing.*;


public class MainProject extends JFrame {

CardLayout cl;

int motherboardP, oddP, hddP, ssdP, fanP, cpuP, gpuP, monitorP, hoursint;
int ramNum, hddNum, ssdNum, fanNum, gpuNum;
double ramP, totalP, powerPerYear;
public float tariff = (float) 0.2180;
public float costRM;

JPanel mainPage, secondPage, thirdPage, results;
//JPanel panelCont;
JLabel title, icon, motherboard, ram, numram,
        numssd, numhdd, odd, numfan, cpu, gpu,
        numgpu, monitor, hours, outage, peryear,
        costyear, watt, kwatt, rm;

JButton start, exit1, exit2, nxt1, bck1, nxt2, bck2, done, bck3, tips, calc;

JTextField numRam, numSSD, numHDD, numFan, numGpu, hoursUse,
        outagePC, perYear, cost;

JComboBox mboardBox, ramBox, oddBox, cpuBox, gpuBox,
        monitorBox;

public MainProject() {
    initComponents();
}

public void initComponents() {

    setTitle("Power Consumption Calculator");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(500, 400);

    Container contentPane = getContentPane();

    contentPane.setLayout(cl);

    /*
    panelCont = new JPanel();
    cl = new CardLayout();
    */

    //contentPane.add(panelCont);

    /*
    panelCont.setLayout(cl);
    panelCont.add(mainPage,"1");
    panelCont.add(secondPage,"2");
    panelCont.add(thirdPage,"3");
    panelCont.add(results,"4");
    cl.show(panelCont,"1");
    */

    mainPage = new JPanel();

    secondPage = new JPanel();

    thirdPage = new JPanel();

    results = new JPanel();

    cl.show(contentPane,"1");

    contentPane.add("1", mainPage);
    contentPane.add("2", secondPage);
    contentPane.add("3", thirdPage);
    contentPane.add("4", results);

    title.setFont(new Font("Tahoma", Font.BOLD, 18));
    title.setText("Computer Power Consumption Calculator");
    motherboard.setText("Motherboard:");
    ram.setText("RAM:");
    numram.setText("No. of RAM Sticks:");
    numssd.setText("Num. of SSD:");
    numhdd.setText("Num. of HDD:");
    odd.setText("Optical Disk Drive:");
    numfan.setText("Num. of Fans:");
    cpu.setText("CPU:");
    gpu.setText("GPU:");
    numgpu.setText("Num. of GPU:");
    monitor.setText("Monitor:");
    hours.setText("Hours of usage/day:");
    outage.setText("PC Power Outage:");
    peryear.setText("Per year:");
    costyear.setText("Cost/year");
    watt.setText("Watts (W)");
    kwatt.setText("kiloWatts(kW)");
    rm.setText("RM");

    icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/Project/pclogo.png")));

    BorderLayout mainL = new BorderLayout();
    mainPage.setLayout(mainL);
    mainPage.add(title, BorderLayout.PAGE_START);
    mainPage.add(icon, BorderLayout.CENTER);
    mainPage.add(start, BorderLayout.SOUTH);
    mainPage.add(exit1,BorderLayout.SOUTH);

    GridLayout secondL = new GridLayout(0,2);
    secondPage.setLayout(secondL);
    secondPage.add(motherboard);
    secondPage.add(mboardBox);
    secondPage.add(ram);
    secondPage.add(ramBox);
    secondPage.add(numram);
    secondPage.add(numRam);
    secondPage.add(numssd);
    secondPage.add(numSSD);
    secondPage.add(numhdd);
    secondPage.add(numHDD);
    secondPage.add(odd);
    secondPage.add(oddBox);
    secondPage.add(numfan);
    secondPage.add(numFan);
    secondPage.add(nxt1);
    secondPage.add(bck1);

    GridLayout thirdL = new GridLayout(0,2);
    thirdPage.setLayout(thirdL);
    thirdPage.add(cpu);
    thirdPage.add(cpuBox);
    thirdPage.add(gpu);
    thirdPage.add(gpuBox);
    thirdPage.add(numGpu);
    thirdPage.add(monitor);
    thirdPage.add(monitorBox);
    thirdPage.add(hours);
    thirdPage.add(hoursUse);
    thirdPage.add(nxt2);
    thirdPage.add(bck2);

    GridLayout resultL = new GridLayout(0,3);
    results.setLayout(resultL);
    results.add(outage);
    results.add(outagePC);
    results.add(watt);
    results.add(peryear);
    results.add(perYear);
    results.add(kwatt);
    results.add(costyear);
    results.add(cost);
    results.add(rm);
    results.add(calc);
    results.add(bck3);
    results.add(exit2);
    results.add(tips);

    start.setText("Start");
    start.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //startActionPerformed(evt);
            cl.show(contentPane,"2");
        }
    });

    exit1.setText("Exit");
    exit1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
           // exit1ActionPerformed(evt);
            System.exit(0);
        }
    });

    exit2.setText("Exit");
    exit2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
           // exit2ActionPerformed(evt);
            System.exit(0);
        }
    });

    nxt1.setText("Next >>");
    nxt1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          //  nxt1ActionPerformed(evt);
            cl.show(contentPane,"3");
            ramNum = Integer.parseInt(numRam.getText());
            ssdNum = Integer.parseInt(numSSD.getText());
            hddNum = Integer.parseInt(numHDD.getText());
            fanNum = Integer.parseInt(numFan.getText());

            JComboBox cb1 = (JComboBox)evt.getSource();
            String mboard = (String)cb1.getSelectedItem();
            if("Average".equals(mboard)) {
              motherboardP = 32;
            }
            if("High End".equals(mboard)) {
              motherboardP = 60;
            }

            JComboBox cb2 = (JComboBox)evt.getSource();
            String ramType = (String)cb2.getSelectedItem();
            if("DDDR1".equals(ramType)) {
                ramP = 5;
            }
            if("DDR2".equals(ramType)) {
                ramP = 4;
            }
            if("DDR3".equals(ramType)) {
                ramP = 2.5;
            }

            JComboBox cb3 = (JComboBox)evt.getSource();
            String typeODD = (String)cb3.getSelectedItem();
            if("DVD".equals(typeODD)) {
                oddP = 22;
            }
            if("BluRay".equals(typeODD)) {
                oddP = 27;
            }


        }
    });

    nxt2.setText("Next >>");
    nxt2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
           // nxt2ActionPerformed(evt);
            cl.show(contentPane,"4");

            gpuNum = Integer.parseInt(numGpu.getText());
            hoursint = Integer.parseInt(hoursUse.getText());

            JComboBox cb4 = (JComboBox)evt.getSource();
            int inCPU = (Integer)cb4.getSelectedIndex();
            switch(inCPU) {
                case 0:
                    cpuP = 89;
                    break;
                case 1:
                    cpuP = 119;
                    break;
                case 2:
                    cpuP = 127;
                    break;
                case 3:
                    cpuP = 125;
                    break;
                case 4:
                    cpuP = 33;
                    break;
                case 5:
                    cpuP = 98;
                    break;

            }

            JComboBox cb5 = (JComboBox)evt.getSource();
            int nvGPU = (Integer)cb5.getSelectedIndex();

            switch(nvGPU) {
                case 0:
                    gpuP = 295;
                    break;
                case 1:
                    gpuP = 100;
                    break;
                case 2:
                    gpuP = 250;
                    break;
                case 3:
                    gpuP = 150;
                    break;
                case 4:
                    gpuP = 105;
                    break;
                case 5:
                    gpuP = 275;
                    break;
            }

            JComboBox cb6 = (JComboBox)evt.getSource();
            int mSize = (Integer)cb6.getSelectedIndex();
            if(mSize == 0) {
                monitorP = 20;
            }
            if(mSize == 1) {
                monitorP = 28;
            }
            if(mSize == 2) {
                monitorP = 50;
            }

        }
    });

    bck1.setText("<< Back");
    bck1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
           // bck1ActionPerformed(evt);
            cl.show(contentPane,"1");
        }
    });

    bck2.setText("<< Back");
    bck2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          //  bck2ActionPerformed(evt);
            cl.show(contentPane,"2");
        }
    });

    bck3.setText("<< Back");
    bck3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
           // bck3ActionPerformed(evt);
            cl.show(contentPane,"3");
        }
    });

    tips.setText("Tips on saving energy");
    tips.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //tipsActionPerformed(evt);
            try {

        String url ="http://www.toptenreviews.com/computers/articles/10-computer-energy-saving-tips-go-green/";

        Desktop dt = Desktop.getDesktop();
        URI uri = new URI(url);
        dt.browse(uri.resolve(uri));
    }    

    catch (URISyntaxException | IOException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
        }
    });

    calc.setText("Calculate");
    calc.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
           // calcActionPerformed(evt);

            gpuP *= gpuNum;
            ramP *= ramNum;
            hddP = hddNum * 5;
            ssdP = ssdNum * 3;
            fanP = fanNum * 4;

            totalP = motherboardP + cpuP + gpuP + ramP +
            hddP + ssdP + monitorP + fanP;
            powerPerYear = totalP * hoursint * 365;

            costRM = (float) ((powerPerYear / 1000) * tariff);

            DecimalFormat df = new DecimalFormat("#.##");
            df.format(costRM);

            String outage = Double.toString(totalP);
            String ppy = Double.toString(powerPerYear);
            String price = Float.toString(costRM);

            outagePC.setText(outage);
            perYear.setText(ppy);
            cost.setText(price);
        }
    });

    mboardBox.setModel(new DefaultComboBoxModel(new String[] { "Average", "High End" }));
    mboardBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
           // mboardBoxActionPerformed(evt);
            JComboBox cb = (JComboBox)evt.getSource();
            String mboard = (String)cb.getSelectedItem();
            if("Average".equals(mboard)) {
              motherboardP = 32;
            }
            if("High End".equals(mboard)) {
              motherboardP = 60;
            }
        }
    });

    ramBox.setModel(new DefaultComboBoxModel(new String[] { "DDR1", "DDR2", "DDR3" }));
    ramBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //ramBoxActionPerformed(evt);
            JComboBox cb = (JComboBox)evt.getSource();
            String ramType = (String)cb.getSelectedItem();
            if("DDDR1".equals(ramType)) {
                ramP = 5;
            }
            if("DDR2".equals(ramType)) {
                ramP = 4;
            }
            if("DDR3".equals(ramType)) {
                ramP = 2.5;
            }
        }
    });

    oddBox.setModel(new DefaultComboBoxModel(new String[] { "DVD", "BluRay" }));
    oddBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //oddBoxActionPerformed(evt);
            JComboBox cb = (JComboBox)evt.getSource();
            String typeODD = (String)cb.getSelectedItem();
            if("DVD".equals(typeODD)) {
                oddP = 22;
            }
            if("BluRay".equals(typeODD)) {
                oddP = 27;
            }
        }
    });

    cpuBox.setModel(new DefaultComboBoxModel(new String[] { "intel Core i3", "intel Core i5", "intel Core i7", "AMD FX 4350", "AMD Sempron 64 3500", "AMD Athlon 64 FX-62" }));
    cpuBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //cpuBoxActionPerformed(evt);
            JComboBox cb = (JComboBox)evt.getSource();
            int inCPU = (Integer)cb.getSelectedIndex();
            switch(inCPU) {
                case 0:
                    cpuP = 89;
                    break;
                case 1:
                    cpuP = 119;
                    break;
                case 2:
                    cpuP = 127;
                    break;
                case 3:
                    cpuP = 125;
                    break;
                case 4:
                    cpuP = 33;
                    break;
                case 5:
                    cpuP = 98;
                    break;

            }

        }
    });

    gpuBox.setModel(new DefaultComboBoxModel(new String[] { "NVidia GTX 500", "NVidia GTX 700", "NVidia GTX Titan", "AMD Radeon HD 2900", "AMD Radeon HD 3870", "AMD Radeon R9 Fury X" }));
    gpuBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //gpuBoxActionPerformed(evt);
            JComboBox cb = (JComboBox)evt.getSource();
            int nvGPU = (Integer)cb.getSelectedIndex();

            switch(nvGPU) {
                case 0:
                    gpuP = 295;
                    break;
                case 1:
                    gpuP = 100;
                    break;
                case 2:
                    gpuP = 250;
                    break;
                case 3:
                    gpuP = 150;
                    break;
                case 4:
                    gpuP = 105;
                    break;
                case 5:
                    gpuP = 275;
                    break;
            }
        }

    });

    monitorBox.setModel(new DefaultComboBoxModel(new String[] { "17\"-19\"", "20\"-22\"", "24\"-30\"" }));
    monitorBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //monitorBoxActionPerformed(evt);
            JComboBox cb = (JComboBox)evt.getSource();
            int mSize = (Integer)cb.getSelectedIndex();
            if(mSize == 0) {
                monitorP = 20;
            }
            if(mSize == 1) {
                monitorP = 28;
            }
            if(mSize == 2) {
                monitorP = 50;
            }
        }

    });


}

public static void go() {

    JFrame frame = new JFrame();
    frame.setVisible(true);
}

public static void main(String[] args) {

    MainProject.go();

}

}

Where do I fix the code and how many bad Java programming practices have I implemented in my code?

回答1:

First...

You need to create an instance of CardLayout BEFORE you apply it to the container and before add any components...

    cl = new CardLayout();
    contentPane.setLayout(cl);

Second...

You should be using the add(Component, Object) method

contentPane.add(mainPage, "1");

Third

public static void go() {

    JFrame frame = new JFrame();
    frame.setVisible(true);
}

Does nothing but creates an empty frame with nothing in it. It might be helpful to actually use MainProject, since it extends from JFrame

Fourth...

Don't extend directly from JFrame, you're not adding any new functionality to the class, it locks you into single use cases and it cause problems like the one you're having.

Instead, consider starting with a JPanel instead...

public class MainProject extends JPanel {

(ps- This change may cause other compiler errors, which I'm not going to try and fix here)

Then simple create a new instance of a JFrame and add your component to it...

public static void go() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            }

            JFrame frame = new JFrame("Testing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new MainProject());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}

Fifth

You might want to take a closer look at...

  • Creating a GUI With JFC/Swing
  • How to Use CardLayout

And...

  • Why is my JLabel not showing up
  • Listener Placement Adhering to the Traditional (non-mediator) MVC Pattern

for some more ideas and how you might better manage the CardLayout

You might also like to have a look at How to Use Tabbed Panes for an alternative