对多个JPanel使用CardLayout且不显示任何内容 [英] Using CardLayout for multiple JPanels and nothing displays

查看:99
本文介绍了对多个JPanel使用CardLayout且不显示任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的(虚假的)计算机功耗计算器.我正在使用卡片布局来放置多个面板,但是当我运行它时,只有一个小窗口不显示任何内容.这是我的长代码,我将其全部放在一个类中.

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();

}

}

我在哪里修复代码,我在代码中实现了几种不良的Java编程实践?

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

推荐答案

第一...

您需要先创建CardLayout的实例,然后再将其应用到容器中,然后再添加任何组件...

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");

第三

public static void go() {

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

不执行任何操作,但创建一个没有任何内容的空框架.实际使用MainProject可能会有所帮助,因为它是从JFrame

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

不要直接从JFrame进行扩展,您不会在类中添加任何新功能,它会将您锁定在单个用例中,并且会引起类似您所遇到的问题.

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.

相反,请考虑以JPanel开头...

Instead, consider starting with a JPanel instead...

public class MainProject extends JPanel {

(ps-此更改可能会导致其他编译器错误,在此不再尝试解决)

然后简单地创建JFrame的新实例,并将您的组件添加到其中...

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

然后...

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

了解更多想法,以及如何更好地管理CardLayout

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

这篇关于对多个JPanel使用CardLayout且不显示任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆