简体   繁体   中英

Why are JButtons not displaying in a JFrame?

I am trying to develop a voting GUI and I have a main class and a ballot class. The Ballot class extends JPanel and creates buttons inside the class. I am trying to add Ballot objects to the main JFrame but when I run the program, the buttons do not display. Any help would be appreciated. Here is the code.

Assig5.java:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.BoxLayout;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;



public class Assig5 extends JFrame
{
    public Assig5()
    {
        super("E-Vote Version 1.0");
        JPanel castVotePanel = new JPanel();
        BoxLayout layout = new BoxLayout(castVotePanel, BoxLayout.Y_AXIS);
        castVotePanel.setLayout(layout);
        ArrayList<String> ballots = new ArrayList<String>();

        try{
            ballots = readBallotFile("ballots.txt");
        }
        catch(FileNotFoundException e){
            System.exit(0);
        }

        ArrayList<Ballot> ballotList = addBallots(ballots);
        for(Ballot b : ballotList)
        {
            add(b);
        }

        castVotePanel.add(createLoginButton());
        castVotePanel.add(createCastButton());

        add(castVotePanel);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String args[])
    {
        Assig5 assig5 = new Assig5();
    }

    public JButton createLoginButton()
    {
        JButton loginButton = new JButton("Login to Vote");
        loginButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                // display/center the jdialog when the button is pressed
                String input = JOptionPane.showInputDialog("Please enter your voter ID: ");
            }
        });
        return loginButton;
    }



    public JButton createCastButton()
    {
        JButton castButton = new JButton("Cast Vote");
        castButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {

            }
        });
        return castButton;
    }

    public ArrayList<Ballot> addBallots(ArrayList<String> ballotContents)
    {
        ArrayList<Ballot> ballotList = new ArrayList<Ballot>();
        for(int i = 0; i < ballotContents.size(); i++)
        {

            String[] splitBallotContent = ballotContents.get(i).split("[:,]");
            String[] options = new String[splitBallotContent.length - 2];
            for(int j = 2; j < splitBallotContent.length; j++)
            {
                options[j - 2] = splitBallotContent[j];
            }
            Ballot ballot = new Ballot(splitBallotContent[0], splitBallotContent[1], options);
            ballotList.add(ballot);
        }
        return ballotList;
    }

    public static ArrayList<String> readBallotFile(String filename) throws FileNotFoundException
    {
        ArrayList<String> list = new ArrayList<String>();
        Scanner s = new Scanner(new File(filename));
        int numBallots = Integer.parseInt(s.nextLine()); //we need to get to next line
        for(int i = 0; i < numBallots; i++)
        {
            if(s.hasNextLine())
            {
                list.add(s.nextLine());
            }

        }
        s.close();
        return list;
    }

Ballot.java:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.BoxLayout;
import java.awt.*;
import java.awt.event.*;

public class Ballot extends JPanel
{
    public Ballot(String ballotID, String title, String[] options)
    {
        super();
        BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
        setLayout(layout);
        add(new JLabel(title, JLabel.CENTER));
        for(String s : options)
        {
            add(new JButton(s));
            //add actionlistener here
        }
    }
}

JFrame uses a BorderLayout , you are adding both the castVotePanel and all the Ballot panels to the same position on the frame ( CENTER ). You might want to consider using a different layout manager

See How to Use BorderLayout and Laying Out Components Within a Container for more details.

For example...

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Assig5 extends JFrame {

    public Assig5() {
        super("E-Vote Version 1.0");
        JPanel castVotePanel = new JPanel();
        BoxLayout layout = new BoxLayout(castVotePanel, BoxLayout.Y_AXIS);
        castVotePanel.setLayout(layout);
        ArrayList<String> ballots = new ArrayList<String>();

        try {
            ballots = readBallotFile("ballots.txt");
        } catch (FileNotFoundException e) {
            System.exit(0);
        }

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        ArrayList<Ballot> ballotList = addBallots(ballots);
        for (Ballot b : ballotList) {
            add(b, gbc);
        }

        castVotePanel.add(createLoginButton());
        castVotePanel.add(createCastButton());

        add(castVotePanel, gbc);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String args[]) {
        Assig5 assig5 = new Assig5();
    }

    public JButton createLoginButton() {
        JButton loginButton = new JButton("Login to Vote");
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // display/center the jdialog when the button is pressed
                String input = JOptionPane.showInputDialog("Please enter your voter ID: ");
            }
        });
        return loginButton;
    }

    public JButton createCastButton() {
        JButton castButton = new JButton("Cast Vote");
        castButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
        return castButton;
    }

    public ArrayList<Ballot> addBallots(ArrayList<String> ballotContents) {
        ArrayList<Ballot> ballotList = new ArrayList<Ballot>();
        int id = 0;
        for (int i = 0; i < 10; i++) {

            String[] options = new String[]{"A", "B", "C", "D"};
            Ballot ballot = new Ballot(Integer.toString(++id), "Help " + id, options);
            ballotList.add(ballot);
        }
        return ballotList;
    }

    public static ArrayList<String> readBallotFile(String filename) throws FileNotFoundException {
        ArrayList<String> list = new ArrayList<String>();
//        Scanner s = new Scanner(new File(filename));
//        int numBallots = Integer.parseInt(s.nextLine()); //we need to get to next line
//        for (int i = 0; i < numBallots; i++) {
//            if (s.hasNextLine()) {
//                list.add(s.nextLine());
//            }
//
//        }
//        s.close();
        return list;

    }

    public class Ballot extends JPanel {

        public Ballot(String ballotID, String title, String[] options) {
            super();
            BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
            setLayout(layout);
            add(new JLabel(title, JLabel.CENTER));
            for (String s : options) {
                add(new JButton(s));
                //add actionlistener here
            }
        }
    }
}

JFrame uses BorderLayout by default and your all panels are on center of border that is why its not showing up

Use different positions or different layouts

for more on layouts : https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html https://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM