Search text file and display results in a JPanel - java

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.
}
}
}
}

Related

How to center buttons in my java game menu

So, basically, I've never really worked with windows in java, and I need help centering things. I tried a bunch of things, but no matter what, I can't center my buttons on my java menu.
Here's my main class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
public class window extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage canvas;
public window(int width, int height) {
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
public Dimension getPreferredSize() {
return new Dimension(canvas.getWidth(), canvas.getHeight());
}
public void paint(Graphics g){
// double CanvasTileHeight = (canvas.getHeight()/16)+1;
// double CanvasTileWidth = (canvas.getWidth()/16)+1;
//
// OpenSimplexNoise noise = new OpenSimplexNoise();
//
// for(int j=0;j<CanvasTileWidth;j++) {
// double NoiseForCurrentLoopPos;
// if (((noise.eval(j,2)+1)*2)+16 < CanvasTileHeight) {
// NoiseForCurrentLoopPos = ((noise.eval(j,2)+1)*2)+16;
// } else {
// NoiseForCurrentLoopPos = CanvasTileHeight;
// }
// for(int i=(int) CanvasTileHeight;i>NoiseForCurrentLoopPos;i--) {
// Image sand = Toolkit.getDefaultToolkit().getImage("src/images/misc/sand.png");
// g.drawImage(sand, j*16, i*16, this);
// }
// }
//
// Image image = Toolkit.getDefaultToolkit().getImage("src/images/misc/Player_Placeholder1.png");
//
// ImageObserver paintingChild = null;
// g.drawImage(image, canvas.getWidth()/2-image.getWidth(paintingChild)/2, canvas.getHeight()/2-image.getHeight(paintingChild)/2, this);
//
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
int width = 640;
int height = 480;
JFrame frame = new JFrame("Example Frame");
window panel = new window(width, height);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
JPanel buttons = new JPanel();
BoxLayout boxlayout = new BoxLayout(buttons, BoxLayout.Y_AXIS);
buttons.setLayout(boxlayout);
buttons.setBorder(new EmptyBorder(new Insets(150, 200, 150, 200)));
JLabel bottomLabel = new JLabel("GAME NAME HERE", SwingConstants.CENTER);
buttons.add(bottomLabel);
JButton jb1 = new JButton("Button 1");
JButton jb2 = new JButton("Button 2");
JButton jb3 = new JButton("Button 3");
jb1.setAlignmentX(SwingConstants.CENTER);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb1);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb2);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb3);
frame.add(buttons);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// loadtest();
// System.out.println(Arrays.toString(((String) test1).split(",")));
//
// savetest();
dirtest();
}
public static void savetest() {
String TestArray[] = {"hi87er629087029648276540982", "hi2", "hi3", "hi4", "Not gonna keep going on like this lol"};
String Test = TestArray[0];
String world = "testworld101022";
for (int k = 0; k < TestArray.length-1; k++) {
Test = Test + "," + TestArray[k+1];
}
new File("src\\saves\\" + world).mkdir();
try(FileOutputStream f = new FileOutputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectOutput s = new ObjectOutputStream(f)) {
s.writeObject(Test);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
static Object test1 = null;
public static void loadtest() {
String world = "testworld101022";
try(FileInputStream in = new FileInputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectInputStream s = new ObjectInputStream(in)) {
test1 = s.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void dirtest() {
File dir = new File("src\\saves");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("No saves yet!");
} else {
for (int i = 0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}
My problem is when I run it, this is what happens:
So, the buttons and/or test are not centered. I don't understand why.
My problem is, the buttons should be about where the red line on the image is, but no matter what I do, I can't get it to work.
I tried centering it with SwingConstants.CENTER, but that diden't work, so I also tried Component.CENTER_ALIGNMENT, but that did the exact same thing. I found that doing multiple different things like changing the code to
jb1.setAlignmentX(Component.CENTER_ALIGNMENT);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
makes it like this:
so basically it makes it so the 2 that are different from the one I changed are correctly centered, but the one I changed it not. All the images and stuff are probably unnecessary, but I hope I got across what I need help with! thanks =)
You can use BoxLayout to do that, take a look at the following code:
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.util.Arrays;
public class Main
{
public static void main(final String[] args)
{
final JLabel label = new JLabel("GAME NAME HERE");
final JButton button1 = new JButton("Button 1");
final JButton button2 = new JButton("Button 2");
final JButton button3 = new JButton("Button 3");
final JPanel centerPanel = createCenterVerticalPanel(5, label, button1, button2, button3);
final JFrame frame = new JFrame();
frame.add(centerPanel);
frame.setVisible(true);
frame.pack();
}
private static JPanel createCenterVerticalPanel(final int spaceBetweenComponents, final JComponent... components)
{
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Arrays.stream(components).forEach(component -> {
component.setAlignmentX(JPanel.CENTER_ALIGNMENT);
panel.add(component);
panel.add(Box.createRigidArea(new Dimension(0, spaceBetweenComponents)));
});
return panel;
}
}
If you also want to center a panel vertically in a frame, just use frame.setLayout(new GridBagLayout()). Cheers!

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

Why won't the JButtons, JLabels and JTextFields be displayed?

This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().

displaying jtextfield data in jlablel on keyPressed event

i need to erase data in jlabel via jtextfield whenever i pressed backspace or delete from current position.I figure out how to add data in jlable(numeric data) but don't know how to erase it or edit it.
//this is my code
String str = "";
private void jTextField1KeyPressed (java.awt.event.KeyEvent evt) {
char ch=evt.getKeyChar();
if(Character.isDigit(ch)
str += ch;
jLabel2.setText(str);
}
}
Use a DocumentListener instead of a KeyListener, it will be able to detect when the user pastes text into the field and/or is changed programmatically
When the Document is updated, get the text from the field and set the labels text. There is little benefit in trying to update another String when the information is already available in the field/Document. If you "really" have to, use a StringBuilder instead, it's more efficient and is mutable
For example
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
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 Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel mirrorLabel;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JTextField field = new JTextField(10);
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
protected void updateLabel(Document document) {
try {
mirrorLabel.setText(document.getText(0, document.getLength()));
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
add(field, gbc);
mirrorLabel = new JLabel(" ");
add(mirrorLabel, gbc);
}
}
}

How can we get 2 combobox selected items only into 3rd combobox dynamically in java swings?

This is what I have done in android ,Here I am having 3 spinners and selecting
2 separate spinner items and those items must be dynamically displaying in
3rd spinner. and I am trying to do in java swings net beans but I am not
getting, how to make please help me.
Here in java swings I am using combo boxes instead of spinner.
public void onItemSelected(AdapterView<?> p, View arg1, int arg2, long arg3) {
switch (p.getId()) {
case R.id.spinnerPetition:
i = spinPetition.getSelectedItem().toString();
spinnerArray1[0] = i;
Log.d("R", "" + Arrays.toString(spinnerArray1));
bind();
break;
case R.id.spinnerRespondent:
j = spinRespondent.getSelectedItem().toString();
spinnerArray1[1] = j;
Log.d("R", "" + Arrays.toString(spinnerArray1));
bind();
break;
default:
break;
}
private void bind() {
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item, spinnerArray1);
spinAppearingFor.setAdapter(spinnerArrayAdapter);
}
Basically, if the third field will never affect the first two, then it's probably easier to use a JTextField, otherwise you will need to build a ComboBox which is the conternation of the first two, so that it contains EVERY possible combination...
import java.awt.EventQueue; 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 javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestFields {
public static void main(String[] args) {
new TestFields();
}
public TestFields() {
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JComboBox cb1;
private JComboBox cb2;
private JTextField field;
public TestPane() {
setLayout(new GridBagLayout());
cb1 = new JComboBox(new Object[]{"Banana", "Pear", "Grapes", "Apples"});
cb2 = new JComboBox(new Object[]{"Monkey", "Elephant", "Dragon", "Gridalo"});
field = new JTextField(10);
field.setEditable(false);
cb1.setSelectedItem(null);
cb2.setSelectedItem(null);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.fill = GridBagConstraints.HORIZONTAL;
add(cb1, gbc);
gbc.gridy++;
add(cb2, gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.gridheight = GridBagConstraints.REMAINDER;
add(field, gbc);
ActionListener handler = new ActionListener() {
public String getDisplayValue(Object value) {
return value == null ? "" : value.toString();
}
#Override
public void actionPerformed(ActionEvent e) {
field.setText(
getDisplayValue(cb1.getSelectedItem()) + "/" +
getDisplayValue(cb2.getSelectedItem()));
}
};
cb1.addActionListener(handler);
cb2.addActionListener(handler);
}
}
}

Categories