Вкладки Java в графическом интерфейсе - PullRequest
2 голосов
/ 11 августа 2010

Я надеюсь, что кто-нибудь может накормить меня этим раствором.Это часть моей основной лаборатории для класса, и это действительно не дает мне слишком много, так как я просто не понимаю, как сделать GUI с вкладками.Я могу сделать обычную программу с некоторым графическим интерфейсом, но я искал и читал и не могу поставить 2 и 2 из-за всей части класса и объявления частных переменных.Итак, я спрашиваю, может ли кто-нибудь сделать мне основной графический интерфейс с 5 вкладками и поместить мой код в 1 вкладку, чтобы я мог выучить и поместить остальные мои коды в другие 4 вкладки.Поэтому я надеюсь, что вы не думаете, что я хочу, чтобы вы давали мне код, когда у меня есть код, я просто не понимаю вкладки, и мы не изучили его в классе.Вот код с собственным графическим интерфейсом, надеюсь, то, что я ввожу, имеет смысл.Я изучаю код, видя, и это поможет мне кучу.

  package landscape;
import javax.swing.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.text.DecimalFormat;

public class Landscape extends JFrame {

    private JFrame mainFrame;
    private JButton calculateButton;
    private JButton exitButton;
    private JTextField lengthField;
    private JLabel lengthLabel;
    private JTextField widthField;
    private JLabel widthLabel;
    private JTextField depthField;
    private JLabel depthLabel;
    private JTextField volumeField;
    private JLabel volumeLabel;
    private JRadioButton builtIn;
    private JRadioButton above;
    private JTabbedPane panel;

    public Landscape()
    {

        JTabbedPane tabs=new JTabbedPane();
        tabs.addTab("Pool", panel);//add a tab for the panel with the title "title"
        //you can add more tabs in the same fashion - obviously you can change the title
        //tabs.addTab("another tab", comp);//where comp is a Component that will occupy the tab
        mainFrame.setContentPane(tabs);//the JFrame will now display the tabbed pane
        mainFrame.setSize(265,200);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
        mainFrame.setResizable(false);
        JPanel panel = new JPanel();//FlowLayout is default

        //Pool
            panel.setOpaque(false);//this tells the panel not to draw its background; looks nicer under LAFs where the background inside a tab is different from that of JPanel
        panel.add(builtIn);
        panel.add(above);
        panel.add(lengthLabel);
        panel.add(lengthField);
        panel.add(widthLabel);
        panel.add(widthField);
        panel.add(depthLabel);
        panel.add(depthField);
        panel.add(volumeLabel);
        panel.add(volumeField);
        panel.add(calculateButton);
        panel.add(exitButton);      
        //creating components
        calculateButton = new JButton ("Calculate");
        exitButton = new JButton ("Exit");
        lengthField = new JTextField (5);
        lengthLabel = new JLabel ("Enter the length of your pool: ");
        widthField = new JTextField (5);
        widthLabel = new JLabel ("Enter the width of your pool: ");
        depthField = new JTextField (5);
        depthLabel = new JLabel ("Enter the depth of your pool: ");
        volumeField = new JTextField (5);
        volumeLabel = new JLabel ("Volume of the pool: ");
        //radio button
        ButtonGroup buttonGroup = new ButtonGroup();
        builtIn = new JRadioButton ("Built in");
        buttonGroup.add(builtIn);
        above = new JRadioButton ("Above");
        buttonGroup.add(above);

        exitButton.setMnemonic('x');
        calculateButton.setMnemonic('C');


        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) 
            { System.exit(0); }
        });

        // create the handlers
        calculateButtonHandler chandler = new calculateButtonHandler(); //instantiate new object
        calculateButton.addActionListener(chandler); // add event listener

        ExitButtonHandler ehandler = new ExitButtonHandler(); 
        exitButton.addActionListener(ehandler); 

        FocusHandler fhandler = new FocusHandler();
        lengthField.addFocusListener(fhandler);
        widthField.addFocusListener(fhandler);
        depthField.addFocusListener(fhandler);

    }

    class calculateButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat num = new DecimalFormat(", ###.##");
            double width;
            double length;
            double depth;
            double volume;
            double volume2;
            double height;
            String instring;

            instring = lengthField.getText();
            if (instring.equals(""))
            {
                instring = "0";
                lengthField.setText("0");
            }
            length = Double.parseDouble(instring);

            instring = widthField.getText();
            if (instring.equals(""))
            {
                instring = "0";
                widthField.setText("0");
            }
            width = Double.parseDouble(instring);

            instring = depthField.getText();
            if (instring.equals(""))
            {
                instring = "0";
                depthField.setText("0");
            }
            depth = Double.parseDouble(instring);

            volume = width * length * depth;
            volumeField.setText(num.format(volume));

            volume2 = width * length * depth;
            }

        }

    class ExitButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }

    class FocusHandler implements FocusListener
    {
        public void focusGained(FocusEvent e)
        {
            if(e.getSource() == lengthField || e.getSource() == widthField || e.getSource() == depthField)
            {
                volumeField.setText("");
            }
            else if (e.getSource() == volumeField)
            {
                volumeField.setNextFocusableComponent(calculateButton);
                calculateButton.grabFocus();
            }
        }

        public void focusLost1(FocusEvent e)
        {
            if(e.getSource() == widthField)
            {
                widthField.setNextFocusableComponent(calculateButton);
            }
        }

        public void focusLost(FocusEvent e)
        {
            if(e.getSource() == depthField)
            {
                depthField.setNextFocusableComponent(calculateButton);
            }
        }
    }

    public static void main(String args[])
    {
        Landscape app = new Landscape();
    }
}

Ответы [ 2 ]

1 голос
/ 11 августа 2010

Вместо того, чтобы получать панель контента и добавлять к ней, просто создайте новую JPanel и добавьте к ней свои материалы.Затем добавьте панель в новый JTabbedPane с любым заголовком и установите панель содержимого JFrame в качестве панели с вкладками.

Вот простой пример того, что вы будете делать:

JPanel panel=new JPanel();//FlowLayout is default
panel.setOpaque(false);//this tells the panel not to draw its background; looks nicer under LAFs where the background inside a tab is different from that of JPanel
panel.add(builtIn);
panel.add(above);
//...you get the picture; add all the stuff you already do, just use panel instead of c
JTabbedPane tabs=new JTabbedPane();
tabs.addTab("title", panel);//add a tab for the panel with the title "title"
//you can add more tabs in the same fashion - obviously you can change the title
tabs.addTab("another tab", comp);//where comp is a Component that will occupy the tab
mainFrame.setContentPane(tabs);//the JFrame will now display the tabbed pane

Вы можете оставить оставшуюся часть кода, как она есть, и она должна нормально работать.

1 голос
/ 11 августа 2010

Учебное пособие и его демо - довольно простые примеры.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...