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
Related
I'm try of change change the text in the option exit , I would like put a title dynamic in with a personality own for example maybe in spanish put "salir" and remove the text default "Exit" I tryed used a variable String and put how atribute in JMenuItem("Exit"); but its give me error,someone say how I can do this?
this is full code :
import java.awt.*
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class BordeExample extends JFrame {
Container frameContainer;
JPanel panel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Ile");
JMenuItem fileExit = new JMenuItem("Exit");
JMenu borderMenu = new JMenu("Border");
String[] borderTypes = {"Bevel", "Compound", "Empty", "Etched", "Line", "Matte", "SoftBevel",
"Titled"};
JRadioButtonMenuItem[] borders = new JRadioButtonMenuItem[borderTypes.length];
AbstractBorder[] border = {new BevelBorder(BevelBorder.LOWERED),
new CompoundBorder(new LineBorder(Color.blue, 10), new LineBorder(Color.red, 5)),
new EmptyBorder(10, 10, 10, 10), new EtchedBorder(), new LineBorder(Color.blue, 10),
new MatteBorder(new ImageIcon("")), new SoftBevelBorder(BevelBorder.RAISED),
new TitledBorder("Example")};
ButtonGroup buttonGroup = new ButtonGroup();
public BordeExample() {
super("");
fileMenu.add(fileExit);
for (int i = 0; i < borderTypes.length; ++i) {
borders[i] = new JRadioButtonMenuItem(borderTypes[i]);
buttonGroup.add(borders[i]);
borderMenu.add(borders[i]);
}
menuBar.add(fileMenu);
menuBar.add(borderMenu);
setJMenuBar(menuBar);
frameContainer = getContentPane();
frameContainer.setLayout(new BorderLayout());
frameContainer.add("Center", panel);
setupEventHandlers();
setSize(700, 700);
setVisible(true);
}
void setupEventHandlers() {
addWindowListener(new WindowHandler());
fileExit.addActionListener(new MenuItemHandler());
for (int i = 0; i < borders.length; ++i) {
borders[i].addItemListener(new ItemHandler());
}
}
public static void main(String[] args) {
BordeExample app = new BordeExample();
}
public class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public class MenuItemHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Exit")) {
System.exit(0);
}
}
}
public class ItemHandler implements ItemListener {
public void itemStateChanged(ItemEvent e) {
JRadioButtonMenuItem button = (JRadioButtonMenuItem) e.getItem();
String label = button.getText();
for (int i = 0; i < borderTypes.length; ++i) {
if (label.equals(borderTypes[i])) {
panel.setBorder(border[i]);
repaint();
}
}
}
}
}
I tryed did that:
String textExample = "salir";
JMenu fileMenu = new JMenu(textExample);
"Code is working :"
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.border.AbstractBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
public class BordeExample extends JFrame {
// It's woring
String exitString = "slair";
JMenuItem fileExit = new JMenuItem(exitString);
//
Container frameContainer;
JPanel panel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Ile");
JMenu borderMenu = new JMenu("Border");
String[] borderTypes = { "Bevel", "Compound", "Empty", "Etched", "Line",
"Matte", "SoftBevel", "Titled" };
JRadioButtonMenuItem[] borders = new JRadioButtonMenuItem[borderTypes.length];
AbstractBorder[] border = {
new BevelBorder(BevelBorder.LOWERED),
new CompoundBorder(new LineBorder(Color.blue, 10), new LineBorder(
Color.red, 5)), new EmptyBorder(10, 10, 10, 10),
new EtchedBorder(), new LineBorder(Color.blue, 10),
new MatteBorder(new ImageIcon("")),
new SoftBevelBorder(BevelBorder.RAISED),
new TitledBorder("Example") };
ButtonGroup buttonGroup = new ButtonGroup();
public BordeExample() {
super("");
fileMenu.add(fileExit);
for (int i = 0; i < borderTypes.length; ++i) {
borders[i] = new JRadioButtonMenuItem(borderTypes[i]);
buttonGroup.add(borders[i]);
borderMenu.add(borders[i]);
}
menuBar.add(fileMenu);
menuBar.add(borderMenu);
setJMenuBar(menuBar);
frameContainer = getContentPane();
frameContainer.setLayout(new BorderLayout());
frameContainer.add("Center", panel);
setupEventHandlers();
setSize(700, 700);
setVisible(true);
}
void setupEventHandlers() {
addWindowListener(new WindowHandler());
fileExit.addActionListener(new MenuItemHandler());
for (int i = 0; i < borders.length; ++i) {
borders[i].addItemListener(new ItemHandler());
}
}
public class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public class MenuItemHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Exit")) {
System.exit(0);
}
}
}
public class ItemHandler implements ItemListener {
public void itemStateChanged(ItemEvent e) {
JRadioButtonMenuItem button = (JRadioButtonMenuItem) e.getItem();
String label = button.getText();
for (int i = 0; i < borderTypes.length; ++i) {
if (label.equals(borderTypes[i])) {
panel.setBorder(border[i]);
repaint();
}
}
}
}
public static void main(String[] args) {
new BordeExample();
}
}
Check Output screenshot :
I have a method like so, which is given an array of JButton and returns their text whenever they are pressed:
public static String foo(JButton[] buttons) {
for (JButton i : buttons) {
i.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
return i.getText();
}
});
}
}
But, of course, this code will not compile because I am returning a variable to a null method. So, how would I have i.getText() return its output too the foo() method?
Edit, all of the code:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JCustomFrame {
public static void showMessageFrame(String title, String message,
String[] textOnButtons, ImageIcon icon) {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.RELATIVE;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5, 5, 5, 5);
JLabel messageLabel = new JLabel(message);
messageLabel.setFont(messageLabel.getFont().deriveFont(16.0f));
panel.add(messageLabel, c);
c.gridy = 1;
c.gridx = 0;
for (int i = 0; i < textOnButtons.length; i++) {
JButton button = new JButton(textOnButtons[i]);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
return ((JButton) arg0.getSource()).getText();
frame.dispose();
}
});
button.setFont(button.getFont().deriveFont(16.0f));
panel.add(button, c);
c.gridx++;
}
if (icon == null) {
frame.setIconImage(new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE));
} else {
frame.setIconImage(icon.getImage());
}
frame.add(panel);
frame.setTitle(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
public static void main(String[] args) {
JCustomFrame.showMessageFrame("Test Frame",
"Do you really want to do this?", new String[] { "Hell No",
"Sure, Why Not" }, null);
}
}
This statement doesn't make sense:
So, how would I have i.getText() return its output too the foo() method?
The method foo() is no longer running after the ActionListeners have been added to the buttons, and certainly will have ended by the time a user pushes a button, as per the rules of event-driven programming. Instead, though you could have the ActionListeners change the state of a class, any class, and that should suffice. For instance:
class FooClass {
private String text;
public void foo(JButton[] buttons) {
for (JButton i : buttons) {
i.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
text = e.getActionCommand();
}
});
}
}
}
If you need greater detail on a viable solution, please tell us more details about your actual program and your specific problem.
Now if you actually needed a method to return the value of the button pressed, you would need to do this via notification mechanisms and a call-back method, but again the details of a solution will depend on the details of the actual problem and code.
Edit
You're trying to emulate a JOptionPane. Your solution is to either use a JOptionPane, adding a JPanel to it, or create your own using a modal JDialog:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JCustomFrame2 {
public static String showMessageFrame(Window owner, String title,
String message, String[] textOnButtons, ImageIcon icon) {
final JDialog dialog = new JDialog(owner);
StringBuilder sb = new StringBuilder();
// make it application modal!
dialog.setModalityType(ModalityType.APPLICATION_MODAL);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.RELATIVE;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5, 5, 5, 5);
JLabel messageLabel = new JLabel(message);
messageLabel.setFont(messageLabel.getFont().deriveFont(16.0f));
panel.add(messageLabel, c);
c.gridy = 1;
c.gridx = 0;
for (int i = 0; i < textOnButtons.length; i++) {
JButton button = new JButton(textOnButtons[i]);
button.addActionListener(new ButtonListener(sb));
button.setFont(button.getFont().deriveFont(16.0f));
panel.add(button, c);
c.gridx++;
}
if (icon == null) {
dialog.setIconImage(new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE));
} else {
dialog.setIconImage(icon.getImage());
}
dialog.add(panel);
dialog.setTitle(title);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.pack();
dialog.setVisible(true);
return sb.toString();
}
private static class ButtonListener implements ActionListener {
private StringBuilder sb;
public ButtonListener(StringBuilder sb) {
this.sb = sb;
}
#Override
public void actionPerformed(ActionEvent e) {
sb.append(e.getActionCommand());
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
if (win != null) {
win.dispose();
}
}
}
public static String showMessageFrame(String title,
String message, String[] textOnButtons, ImageIcon icon) {
return showMessageFrame(null, title, message, textOnButtons, icon);
}
public static void main(String[] args) {
String result = JCustomFrame2.showMessageFrame("Test Frame",
"Do you really want to do this?", new String[] { "Hell No",
"Sure, Why Not" }, null);
System.out.println(result);
}
}
Why so complicated? whatever foo is supposed to do, it would be a lot easier to simply call another method from inside the ActionListener with the name of the button as argument. Or, if you really want to achieve something like this, make the thread wait for the user to press a button.
public void doSomething(){
JButton[] someButtons = ...;//whereever you create the buttons
System.out.println(foo(someButtons));
}
public static String foo(JButton[] buttons){
final String someString = "";
final Object lock = new Object();
for(JButton b : buttons){
b.addActionListener(e -> {
someString.concat(b.getName());
synchronized(lock){
lock.notifyAll();
}
});
}
synchronized(lock){
try{
lock.wait();
}catch(InterruptedException e){}
}
return someString;
}
My program will allow the user to log in first and if he is logged in,
he will click on labelone first and labeltwo next.
the program will print ("last two cards detected. starting new game..") and allow the user to click on the two labels again.
the problem I am facing is after my panel has been repainted. I cannot click on the labels
anymore.
I know that my codes provided it too lengthy but I have already attempted to tried to cut down my codes from my actual program.
I think the main focus is this block of codes in my controller class.
labelPanel.removeAll();
Dealer dealer = new Dealer();
labelPanel.add(new LabelPanel(dealer));
labelPanel.revalidate();
labelPanel.repaint();
new Controller(labelPanel,dealer);
I am not sure what happened to my mouselistener. please help
This is are the class. feel free to run it if you guys couldn't understand.
login as username-> john password -> abc
click on label one first, after that click on label two. the console will display
"last 2 cards detected, starting new game.."
after that try clicking the labels again(by right it should be clickable but it's not)
LoginPanel.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class LoginPanel extends JPanel {
private JPanel northPanel = new JPanel(new BorderLayout());
private JPanel southPanel = new JPanel(new BorderLayout());
private JPanel subSouthPanel = new JPanel(new GridBagLayout());
private JPanel subSouthPanelTwo = new JPanel(new FlowLayout());
private GridBagConstraints gbc2 = new GridBagConstraints();
private JTextField playerUsernameTF = new JTextField(15);
private JPasswordField playerPasswordTF = new JPasswordField(15);
private JButton playerLoginBtn = new JButton("Login");
public LoginPanel() {
setLayout(new BorderLayout());
gbc2.gridx = 0;
gbc2.gridy = 0;
subSouthPanel.add(new JLabel("Username"),gbc2);
gbc2.gridx = 1;
gbc2.gridy = 0;
subSouthPanel.add(playerUsernameTF,gbc2);
gbc2.gridx = 0;
gbc2.gridy = 1;
subSouthPanel.add(new JLabel("Password"),gbc2);
gbc2.gridx = 1;
gbc2.gridy = 1;
subSouthPanel.add(playerPasswordTF,gbc2);
southPanel.add(subSouthPanel,BorderLayout.CENTER);
subSouthPanelTwo.add(playerLoginBtn);
southPanel.add(subSouthPanelTwo,BorderLayout.SOUTH);
add(northPanel,BorderLayout.NORTH);
add(southPanel,BorderLayout.SOUTH);
}
public JTextField getPlayerUsernameTF() {
return playerUsernameTF;
}
public JPasswordField getPlayerPasswordTF() {
return playerPasswordTF;
}
void addListenerForPlayerLoginBtn(ActionListener actionListener) {
playerLoginBtn.addActionListener(actionListener);
}
}
LabelPanel.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class LabelPanel extends JPanel {
private JPanel panel = new JPanel(new FlowLayout());
private JLabel labelOne;
private JLabel labelTwo;
public LabelPanel(Dealer dealer) {
setLayout(new BorderLayout());
labelOne = new JLabel(new ImageIcon(dealer.hideCard()));
labelTwo = new JLabel(new ImageIcon(dealer.hideCard()));
panel.add(labelOne);
panel.add(labelTwo);
add(panel);
}
public JLabel getJLabelOne() {
return labelOne;
}
public JLabel getJLabelTwo() {
return labelTwo;
}
void listenerForJLabelOne(MouseListener listenForMouseClick) {
labelOne.addMouseListener(listenForMouseClick);
}
void listenerForJLabelTwo(MouseListener listenForMouseClick) {
labelTwo.addMouseListener(listenForMouseClick);
}
}
Dealer.java
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Dealer {
public Dealer() {
}
public Image hideCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/blank.png"));
} catch (Exception e) {
}
return img;
}
public Image displayFirsCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/ClubsAce.png"));
} catch (Exception e) {
}
return img;
}
public Image displaySecondCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/ClubsAce.png"));
} catch (Exception e) {
}
return img;
}
}
Controller.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.Timer;
public class Controller {
private LabelPanel labelPanel;
private Dealer dealer;
private int countdown = 1;
private Timer timer = new Timer(1000,null);
private MouseHandler mouseHandler = new MouseHandler();
private int clicked = 0;
public Controller(LabelPanel labelPanel,Dealer dealer) {
clicked = 0;
this.labelPanel = labelPanel;
this.dealer = dealer;
this.labelPanel.listenerForJLabelOne(mouseHandler);
this.labelPanel.listenerForJLabelTwo(mouseHandler);
this.labelPanel.getJLabelOne().setText("Ace");
this.labelPanel.getJLabelTwo().setText("Ace");
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
clicked++;
if(clicked == 1) {
labelPanel.getJLabelOne().setIcon((new ImageIcon(dealer.displayFirsCard())));
}
if(clicked == 2) {
labelPanel.getJLabelTwo().setIcon((new ImageIcon(dealer.displaySecondCard())));;
if(label.getText().equals(label.getText())) {
System.out.println("last 2 cards detected, starting new game..");
timer = new Timer(1000,new newGameTimer());
timer.start();
}
}
}
}
private class newGameTimer implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(countdown == 0) {
timer.stop();
clicked = 0;
labelPanel.removeAll();
Dealer dealer = new Dealer();
labelPanel.add(new LabelPanel(dealer));
labelPanel.revalidate();
labelPanel.repaint();
new Controller(labelPanel,dealer);
}
else {
countdown--;
}
}
}
}
MainFrame.java
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame {
private CardLayout cardLayout = new CardLayout();
private Dealer dealer = new Dealer();
private JPanel cardLayoutPanel = new JPanel();
private LoginPanel loginPanel = new LoginPanel();
private JFrame frame = new JFrame("Mouse CLick Test");
private JPanel dialogPanel = new JPanel();
private LabelPanel labelPanel = new LabelPanel(dealer);
public MainFrame() {
cardLayoutPanel.setLayout(cardLayout);
cardLayoutPanel.add(loginPanel,"1");
cardLayout.show(cardLayoutPanel,"1");
cardLayoutPanel.add(labelPanel,"2");
frame.add(cardLayoutPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(1024,768);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
loginPanel.addListenerForPlayerLoginBtn(new PlayerLoginBtnActionPerformed());
}
public class PlayerLoginBtnActionPerformed implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String playerUsername = loginPanel.getPlayerUsernameTF().getText();
String playerPassword = new String(loginPanel.getPlayerPasswordTF().getPassword());
if(playerUsername.equals("john") && playerPassword.equals("abc")) {
JOptionPane.showMessageDialog(dialogPanel,
"Login Successfully!"
,"Player Login",JOptionPane.PLAIN_MESSAGE);
cardLayout.show(cardLayoutPanel,"2");
new Controller(labelPanel,dealer);
}
else {
JOptionPane.showMessageDialog(dialogPanel,
"Wrong Password or Username!"
,"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[]args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
The problem is, you are adding a LabelPanel to a LabelPanel
labelPanel.add(new LabelPanel(dealer));
But you are passing the outer panel to the controller
new Controller(labelPanel, dealer);
The outer panel no longer actually contains any labels, but only contains the new LabelPanel...
A better solution would be to provide the LabelPanel with a "reset" option of some kind instead...
I have a grid of JTextFields for my sudoku gui but im confused as to how to place for example a 3 in the top left box, in the top left corner of that box so it looks something like this
http://tinypic.com/r/t7io28/8
and that number becomes un editable to the user?
Here's my class for setting the cells:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class Squares extends JPanel {
public final int CELL_COUNT = 9;
public Cell [] cells = new Cell[CELL_COUNT];
public Squares(){
this.setLayout(new GridLayout(3,3));
this.setBorder(new LineBorder(Color.BLACK,2));
for(int i = 0; i<CELL_COUNT; i++){
cells[i] = new Cell();
cells[i].setDocument(new NumericalDocument());
this.add(cells[i]);
}
}
public class Cell extends JTextField{
private int number;
public Cell(){
}
public void setNumber(int number){
this.number = number;
this.setText("5");
}
public int getNumber(){
return number;
}
}
public static class NumericalDocument extends PlainDocument{
String numbers = "0123456789";
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (getLength() == 0 && str.length() == 1 && numbers.contains(str)) {
super.insertString(offs, str, a);
}
else {
Toolkit.getDefaultToolkit().beep();
}
}
}
}
and here's the class that sets the 3x3 cells into a 3x3 grid
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class SudokuPanel extends JFrame {
public final int SQUARE_COUNT = 9;
public Squares [] squares = new Squares[SQUARE_COUNT];
public SudokuPanel(){
super("Sudoku");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3,3));
for(int i=0; i<SQUARE_COUNT; i++){
squares[i] = new Squares();
panel.add(squares[i]);
}
JPanel panel2 = new JPanel();
JButton startTime = new JButton();
JButton stop = new JButton();
JButton submit = new JButton();
MyTimer timer = new MyTimer();
startTime = new JButton("Start Timer");
stop = new JButton("Stop Timer");
final JLabel timerLabel = new JLabel(" ...Waiting... ");
submit = new JButton("Done");
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
JMenuItem newDifficulty = new JMenuItem("Select New Difficulty");
menu.add(newDifficulty);
JMenuItem reset = new JMenuItem("Reset Puzzle");
menu.add(reset);
JMenuItem exit = new JMenuItem("Exit");
menu.add(exit);
exitaction e = new exitaction();
newDifficultyaction d = new newDifficultyaction();
resetaction f = new resetaction();
reset.addActionListener(f);
exit.addActionListener(e);
newDifficulty.addActionListener(d);
panel2.add(timer);
add(panel, BorderLayout.CENTER);
add(panel2, BorderLayout.PAGE_END);
setVisible(true);
setLocationRelativeTo(null);
}
public class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
public class newDifficultyaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
Level select = new Level();
}
}
public class resetaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
SudokuPanel Squares = new SudokuPanel();
}
}
}
A JTextField can be set uneditable using setEditable(false). You could also use JLabels.
Does anyone have any ideas on how I can search a text file and list the results in a JComponent, like a JPanel.
I've been trying to make this work out for two days now, but no success will really appreciate a reply. Thanks a lot in advance.
I've been trying to write a class that handles search queries to a text file. My main goal is to get the lines in a text file that contain the search keywords entered in a JTextField and print them out in an appropriate JComponent(something like a JTextField, JTextPane, whichever best applicable).
I'd like the search results to show in columns like how google search results get displayed, so that each line from the text file gets printed in its own line. I've been told that it's best to use an ArrayList. I really don't know how to do this. I've picked up ideas from all over and this is what I have so far:
Much appreciation in advance. I am very new to Java. I've been at it the whole day trying to get this right and have not gone any far. Am willing to try anything offered, even a new approach.
// The class that handles the search query
// Notice that I've commented out some parts that show errors
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTextPane;
public class Search {
public static String path;
public static String qri;
public Search(String dTestFileDAT, String qry) {
path = dTestFileDAT;
qri = qry;
}
public static JTextPane resultJTextPane;
public static List<String> linesToPresent = new ArrayList<String>();
public static List<String> searchFile(String path, String match){
File f = new File(path);
FileReader fr;
try {
fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
do{
line = br.readLine();
Pattern p = Pattern.compile(match);
Matcher m = p.matcher(line);
if(m.find())
linesToPresent.add(line);
} while(line != null);
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// resultJTextPane = new JTextPane();
// resultJTextPane = (JTextPane) Home.BulletinsJPanel.add(linesToPresent);
return linesToPresent;
}
}
// This handles the click event to take the query. Notice that I've commented out some parts that show errors
private void mouseClickedSearch(java.awt.event.MouseEvent evt) {
Search fs = new Search("/D:/TestFile.dat/", "Text to search for");
// searchResultsJPanel.add(Search.searchFile("/D:/TestFile.dat/", "COLE"));
// searchResultsJTextField.add(fs);
}
There are a number of possible solutions, this is just a simple one (no seriously, it is ;))
Basically, this just uses a JList to store all the matches of the search text from the search file.
This is a case sensitive search, so beware
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MySearch {
public static void main(String[] args) {
new MySearch();
}
public MySearch() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField findText;
private JButton search;
private DefaultListModel<String> model;
public TestPane() {
setLayout(new BorderLayout());
JPanel searchPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
searchPane.add(new JLabel("Find: "), gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
findText = new JTextField(20);
searchPane.add(findText, gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
search = new JButton("Search");
searchPane.add(search, gbc);
add(searchPane, BorderLayout.NORTH);
model = new DefaultListModel<>();
JList list = new JList(model);
add(new JScrollPane(list));
ActionHandler handler = new ActionHandler();
search.addActionListener(handler);
findText.addActionListener(handler);
}
public class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
model.removeAllElements();
// BufferedReader reader = null;
String searchText = findText.getText();
try (BufferedReader reader = new BufferedReader(new FileReader(new File("search.txt")))) {
String text = null;
while ((text = reader.readLine()) != null) {
if (text.contains(searchText)) {
model.addElement(text);
}
}
} catch (IOException exp) {
exp.printStackTrace();
JOptionPane.showMessageDialog(TestPane.this, "Could not create file", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
You could also take another tact and simply highlight the matches...
This uses a slightly different approach as this is interactive. Basically you simply type, wait a 1/4 second and it will start searching...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class MySearch02 {
public static void main(String[] args) {
new MySearch02();
}
public MySearch02() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField findText;
private JTextArea ta;
private Timer keyTimer;
public TestPane() {
setLayout(new BorderLayout());
JPanel searchPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
searchPane.add(new JLabel("Find: "), gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
findText = new JTextField(20);
searchPane.add(findText, gbc);
add(searchPane, BorderLayout.NORTH);
ta = new JTextArea(20, 40);
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
ta.setEditable(false);
add(new JScrollPane(ta));
loadFile();
keyTimer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String find = findText.getText();
Document document = ta.getDocument();
try {
for (int index = 0; index + find.length() < document.getLength(); index++) {
String match = document.getText(index, find.length());
if (find.equals(match)) {
javax.swing.text.DefaultHighlighter.DefaultHighlightPainter highlightPainter =
new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
ta.getHighlighter().addHighlight(index, index + find.length(),
highlightPainter);
}
}
} catch (BadLocationException exp) {
exp.printStackTrace();
}
}
});
keyTimer.setRepeats(false);
findText.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
keyTimer.restart();
}
#Override
public void removeUpdate(DocumentEvent e) {
keyTimer.restart();
}
#Override
public void changedUpdate(DocumentEvent e) {
keyTimer.restart();
}
});
}
protected void loadFile() {
String searchText = findText.getText();
try (BufferedReader reader = new BufferedReader(new FileReader(new File("search.txt")))) {
ta.read(reader, "Text");
} catch (IOException exp) {
exp.printStackTrace();
JOptionPane.showMessageDialog(TestPane.this, "Could not create file", "Error", JOptionPane.ERROR_MESSAGE);
}
ta.setCaretPosition(0);
}
}
}
Try this:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringJoiner;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SearchTextFile {
public static void main(String[] args) {
new SearchTextFile();
}
public SearchTextFile() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Bible Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField findText;
private JButton search;
private DefaultListModel<String> model;
private JList list;
private String searchPhrase;
public TestPane() {
setLayout(new BorderLayout());
JPanel searchPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
searchPane.add(new JLabel("Find: "), gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
findText = new JTextField(20);
searchPane.add(findText, gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
search = new JButton("Search");
searchPane.add(search, gbc);
add(searchPane, BorderLayout.NORTH);
model = new DefaultListModel<>();
list = new JList(model);
list.setCellRenderer(new HighlightListCellRenderer());
add(new JScrollPane(list));
ActionHandler handler = new ActionHandler();
search.addActionListener(handler);
findText.addActionListener(handler);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Script.txt")))) {
String text = null;
while ((text = reader.readLine()) != null) {
model.addElement(text);
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
public class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
searchPhrase = findText.getText();
if (searchPhrase != null && searchPhrase.trim().length() == 0) {
searchPhrase = null;
}
list.repaint();
// model.removeAllElements();
//// BufferedReader reader = null;
//
// String searchText = findText.getText();
// try (BufferedReader reader = new BufferedReader(new FileReader(new File("bible.txt")))) {
//
// String text = null;
// while ((text = reader.readLine()) != null) {
//
// if (text.contains(searchText)) {
//
// model.addElement(text);
//
// }
//
// }
//
// } catch (IOException exp) {
//
// exp.printStackTrace();
// JOptionPane.showMessageDialog(TestPane.this, "Something Went Wrong", "Error", JOptionPane.ERROR_MESSAGE);
//
// }
}
}
public class HighlightListCellRenderer extends DefaultListCellRenderer {
public final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))";
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof String && searchPhrase != null) {
String text = (String) value;
if (text.contains(searchPhrase)) {
text = text.replace(" ", " ");
value = "<html>" + text.replace(searchPhrase, "<font color=#ffff00>" + searchPhrase + "</font>") + "</html>";
}
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
}
}
}
}