I have run into a problem with what I thought was a pretty simple program. I simply want to use a GUI, click and button to display data in a text file. I seem to be close but am running into a problem I do not understand. If I leave the code the way it is here I get the error that highScores is not declared (symbol not found) for line 72. But if I try to declare highSchores the I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown" for line 69. Any idea what I am doing wrong and how I can fix it?
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class tetrisScores extends JFrame{
private JPanel contentPanel;
private JButton btnSearch;
private JButton btnLoad;
private JButton btnSort;
private JRadioButton firstSort;
private JRadioButton secondSort;
private JTextField searchInput;
private JTextArea output;
private String[] highScores;
private void add (Container con, Component widget, int left, int top, int width, int height) //creates variables for bounds
{
widget.setBounds(left, top, width, height); //sets setBounds to created variables
con.add(widget); //tells program container to use widget's bounds
}
tetrisScores()
{
contentPanel=(JPanel)getContentPane();
contentPanel.setLayout(null);
btnLoad = new JButton("Load File");
add(contentPanel, btnLoad, 10, 10, 360, 40);
searchInput = new JTextField("");
add(contentPanel, searchInput, 10, 60, 240, 40);
btnSearch = new JButton("Search");
add(contentPanel, btnSearch, 260, 60, 110, 40);
firstSort = new JRadioButton("Bubble Sort");
add(contentPanel, firstSort, 20, 110, 110, 40);
firstSort = new JRadioButton("Linear Sort");
add(contentPanel, firstSort, 140, 110, 110, 40);
btnSearch = new JButton("Sort");
add(contentPanel, btnSearch, 260, 110, 110, 40);
output = new JTextArea("");
add(contentPanel, output, 10, 160, 360, 150);
output.setEditable(false);
setTitle("High Scores");
setSize(500,500);
setLocation(new Point (150,150));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
btnLoad.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent add)
{
OpenFile();
for (int j = 0; j<10;j++)
{
output.append(highScores[j] + "/n");
}
}
});
}
public String [] OpenFile() throws IOException
{
FileReader fr = new FileReader("tetrishighscore.txt");
BufferedReader scoreReader = new BufferedReader (fr);
int numbLines = 10;
String[] textData = new String [numbLines];
int i;
for (i=0; i < numbLines; i++)
{
textData[i] = scoreReader.readLine();
}
scoreReader.close();
return textData;
}
public static void main (String [] args)
{
new tetrisScores();
}
}
The OpenFile() method throws an IOException, but it is never caught.
I have made some modifications:
highScores could be declared as a List (so you don't have to give the number of lines in advance)
the Exception is caught
the line break character is "\n", not "/n"
Some more modifications could be made, but this should work:
import java.awt.Component;
import java.awt.Container;
import java.util.List;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class TetrisScores extends JFrame {
private JPanel contentPanel;
private JButton btnSearch;
private JButton btnLoad;
private JButton btnSort;
private JRadioButton firstSort;
private JRadioButton secondSort;
private JTextField searchInput;
private JTextArea output;
private List<String> highScores = new ArrayList<>();
private void add(Container con, Component widget, int left, int top, int width, int height) // creates variables for
// bounds
{
widget.setBounds(left, top, width, height); // sets setBounds to created variables
con.add(widget); // tells program container to use widget's bounds
}
TetrisScores() {
contentPanel = (JPanel) getContentPane();
contentPanel.setLayout(null);
btnLoad = new JButton("Load File");
add(contentPanel, btnLoad, 10, 10, 360, 40);
searchInput = new JTextField("");
add(contentPanel, searchInput, 10, 60, 240, 40);
btnSearch = new JButton("Search");
add(contentPanel, btnSearch, 260, 60, 110, 40);
firstSort = new JRadioButton("Bubble Sort");
add(contentPanel, firstSort, 20, 110, 110, 40);
firstSort = new JRadioButton("Linear Sort");
add(contentPanel, firstSort, 140, 110, 110, 40);
btnSearch = new JButton("Sort");
add(contentPanel, btnSearch, 260, 110, 110, 40);
output = new JTextArea("");
add(contentPanel, output, 10, 160, 360, 150);
output.setEditable(false);
setTitle("High Scores");
setSize(500, 500);
setLocation(new Point(150, 150));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent add) {
try {
OpenFile();
for (int j = 0; j < highScores.size(); j++) {
output.append(highScores.get(j) + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void OpenFile() throws IOException {
FileReader fr = new FileReader("tetrishighscore.txt");
BufferedReader scoreReader = new BufferedReader(fr);
String line;
while((line = scoreReader.readLine()) != null) {
highScores.add(line);
}
scoreReader.close();
}
public static void main(String[] args) {
new TetrisScores();
}
}
Related
Working on a side project for a professor that wants a random number generator.
The program in its current state leaves a lot to be desired but I think I'm on the right track. However, I am stuck when it comes to using the text field, passing that data to my random number equation, and displaying it. Basically, the program isn't waiting for the user input to the text field.
We never made it past OOP in school so I need to pull out the big guns (you guys).
Here is what I am working with currently. The last bit at the end is the part that I am having issue with.
package RandomButton;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
public class GUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField ClassSize;
private JLabel label;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI() {
int x;
int max;
String strMax;
String strX;
Scanner kb = new Scanner(System.in);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Text field code
textField = new JTextField();
textField.setText("1");
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setBounds(10, 143, 414, 35);
contentPane.add(textField);
textField.setColumns(10);
//Randomize button code
JButton btnNewButton = new JButton("Randomize!");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 40));
btnNewButton.setBounds(10, 196, 414, 54);
contentPane.add(btnNewButton);
//Label code
label = new JLabel();
label.setFont(new Font("Tahoma", Font.PLAIN, 70));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(10, 11, 414, 103);
contentPane.add(label);
//math code
Random num = new Random();
strMax = textField.getText();
max = Integer.parseInt(strMax);
x = num.nextInt(max) + 1;
strX = String.valueOf(x);
label.setText(strX);
}
}
What you need is to add an ActionListener, see javadoc here
Simple modification of the code, without bigger discussion, is to move up the code that simulate random numbers...
//Randomize button code
JButton btnNewButton = new JButton("Randomize!");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 40));
btnNewButton.setBounds(10, 196, 414, 54);
contentPane.add(btnNewButton);
// the listener
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random num = new Random();
String strMax = textField.getText();
int max = Integer.parseInt(strMax);
int x = num.nextInt(max) + 1;
String strX = String.valueOf(x);
label.setText(strX);
}
} );
So, I have been trying to figure this out for a little bit and cannot figure out how to do it. I want one of my buttons in another class to change the text of a JLabel in the GUI class.
Here is the code from GUI class:`import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class GUI extends JFrame{
Container pane = getContentPane();
JButton guess = new JButton("Guess");
JButton gen = new JButton("Generate number");
JTextField userInput = new JTextField();
JLabel Numbers = new JLabel("Press generate to start.");
JLabel guessedNum = new JLabel("");
JLabel error = new JLabel("");
public void CreateGUI(){
final int WIDTH = 325;
final int HEIGHT = 200;
final int centerWIDTH = WIDTH / 4;
final int centerHEIGHT = HEIGHT / 4;
guessHandler guessHandle;
genHandler genHandle;
pane.setLayout(null);
guessHandle = new guessHandler();
guess.addActionListener(guessHandle);
genHandle = new genHandler();
gen.addActionListener(genHandle);
userInput.setBounds(centerWIDTH - 20, centerHEIGHT, 200, 20);
guess.setBounds(userInput.getX() - 35, (userInput.getY() + 25), 105, 50);
gen.setBounds((guess.getX() + 105), guess.getY(), 165, 50);
error.setBounds(70, 125, 300, 20);
Numbers.setBounds(90, 0, 300, 20);
guessedNum.setBounds(20, 25, 300, 20);
pane.add(userInput);
pane.add(guess);
pane.add(gen);
pane.add(Numbers);
pane.add(guessedNum);
pane.add(error);
setSize(WIDTH,HEIGHT);
setTitle("Number Guesser");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setLocation(350, 150);
}
}
And here the code from the button trying to change the JLabel "error":
`
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class guessHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
GUI gui = new GUI();
gui.changePOS(4, 50, 0, 300, 20);
gui.error.setText("HI from guessHandler.java");
}
}
First, add a getter with public access so your second class can access the field. Something like,
public JLabel getError() {
return error;
}
Or (as #MadProgrammer suggested in the comments, a mutator) like
public void setError(String txt) {
error.setText(txt);
}
Then modify your second class, and pass the instance of GUI to it in the constructor. Like,
public class guessHandler implements ActionListener{
private GUI gui;
public guessHandler(GUI gui) {
this.gui = gui;
}
public void actionPerformed(ActionEvent e) {
gui.changePOS(4, 50, 0, 300, 20);
gui.setError("HI from guessHandler.java");
}
}
for my program I currently want to use the open button to open a JFileChooser and select an image and then draw it on the JPanel on the left side of the applet, I know that the file is being retrieved but when i go to repaint the graphics context nothing happens. Thanks in advance.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
public class FinalProject390 {
public static void main(String[] args) {
createAndShowGUI();
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Final Project");
f.setSize(1025, 520);
f.add(new GraphicsPanel());
f.add(new MainPanel());
f.setVisible(true);
}
}
class MainPanel extends JPanel implements ActionListener {
JButton openButton = new JButton("Open");
JButton newButton = new JButton("New");
JButton saveButton = new JButton("Save");
JButton saveAsButton = new JButton("Save As");
JButton drawLineButton = new JButton("Draw Line");
JButton drawRectangleButton = new JButton("Draw Rectangle");
JButton drawOvalButton = new JButton("Draw Oval");
JButton drawArcButton = new JButton("Draw Arc");
JButton extractPixelDataButton = new JButton("Extract Pixel Data");
JButton convoluteButton = new JButton("Convolute");
JTextField xPosStartField = new JTextField("x-Position Start");
JTextField yPosStartField = new JTextField("y-Position Start");
JTextField xPosEndField = new JTextField("x-Position End");
JTextField yPosEndField = new JTextField("y-Position End");
JTextField angleStartField = new JTextField("Angle Start");
JTextField angleSizeField = new JTextField("Angle Size");
public MainPanel() {
openButton.setBounds(660, 50, 100, 30);
openButton.addActionListener(this);
newButton.setBounds(780, 50, 100, 30);
saveButton.setBounds(900, 50, 100, 30);
drawLineButton.setBounds(660, 110, 160, 30);
drawRectangleButton.setBounds(840, 110, 160, 30);
drawOvalButton.setBounds(660, 155, 160, 30);
drawArcButton.setBounds(840, 155, 160, 30);
extractPixelDataButton.setBounds(660, 220, 160, 30);
convoluteButton.setBounds(840, 220, 160, 30);
xPosStartField.setBounds(660, 280, 100, 30);
yPosStartField.setBounds(660, 320, 100, 30);
xPosEndField.setBounds(660, 380, 100, 30);
yPosEndField.setBounds(660, 420, 100, 30);
angleStartField.setBounds(900, 280, 100, 30);
angleSizeField.setBounds(900, 320, 100, 30);
setLayout(null);
setBackground(Color.green);
setBounds(641, 0, 370, 480);
add(openButton);
add(newButton);
add(saveButton);
add(drawLineButton);
add(drawRectangleButton);
add(drawOvalButton);
add(drawArcButton);
add(extractPixelDataButton);
add(convoluteButton);
add(xPosStartField);
add(yPosStartField);
add(xPosEndField);
add(yPosEndField);
add(angleStartField);
add(angleSizeField);
}
#Override
public void actionPerformed(ActionEvent e) {
javax.swing.JFileChooser fileChooser = new JFileChooser();
BufferedImage bin = null, bi = null;
GraphicsPanel gPanel = new GraphicsPanel();
fileChooser.setCurrentDirectory(new File(System
.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: "
+ selectedFile.getAbsolutePath());
try {
bin = ImageIO.read(new File(selectedFile.getAbsolutePath()));
} catch (IOException e1) {
e1.printStackTrace();
}
gPanel.setImg(bin);
}
}
}
class GraphicsPanel extends JPanel {
BufferedImage bi = null, bin = null;
public GraphicsPanel() {
setLayout(null);
setBackground(Color.blue);
setSize(640, 480);
setLocation(0, 0);
}
public void setImg(BufferedImage b) {
this.bi = b;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
}
This looks like a homework assignment, so rather than an outright answer with code, instead please consider the following:
In your method createAndShowGUI() you instantiate a GraphicsPanel object and add it to a JFrame
In your actionPerformed() method, you instantiate another GraphicsPanel object (which is never added to the JFrame) and you call setImage().
Your image does not display because the GraphicsPanel control that has been added to your JFrame is not the same GraphicsPanel control that you set the image on.
I hope this will be enough to help you fix your code.
So i got this Actionlistener (Check code below)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import java.awt.TextArea;
import javax.swing.JTextPane;
import java.awt.Component;
import java.awt.TextField;
import java.awt.Label;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.util.Arrays;
import javax.swing.JComboBox;
import java.awt.event.ActionEvent;
public class Frame extends Register {
private int TempInt;
JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run() {
try {
Frame window = new Frame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void windowClosing (WindowEvent e) {
JOptionPane.showMessageDialog(frame, "Programmet sparas och kommer nu stängas av");
System.exit(1);
}
/**
* Create the application.
*/
public Frame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 424);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final TextArea textArea = new TextArea();
textArea.setEditable(false);
textArea.setBounds(0, 105, 440, 243);
frame.getContentPane().add(textArea);
// Använd k.setBelopp beroende på vilken man väljer
String s = "";
int il = beraknaSaldo();
s = Integer.toString(il);
JTextPane saldoText = new JTextPane();
saldoText.setText(s);
saldoText.setEditable(false);
saldoText.setBounds(208, 354, 42, 22);
frame.getContentPane().add(saldoText);
final TextField beloppField = new TextField();
beloppField.setEditable(false);
beloppField.setBounds(120, 10, 102, 22);
frame.getContentPane().add(beloppField);
final TextField tidField = new TextField();
tidField.setEditable(false);
tidField.setBounds(255, 10, 102, 22);
frame.getContentPane().add(tidField);
Label saldoLabel = new Label("Saldo:");
saldoLabel.setBounds(162, 354, 40, 22);
frame.getContentPane().add(saldoLabel);
Label beloppLabel = new Label("Belopp:");
beloppLabel.setBounds(72, 10, 50, 22);
frame.getContentPane().add(beloppLabel);
Label tidLabel = new Label("Tid:");
tidLabel.setBounds(228, 10, 22, 22);
frame.getContentPane().add(tidLabel);
Label besökartypLabel = new Label("Bes\u00F6kartyp");
besökartypLabel.setBounds(0, 77, 62, 22);
frame.getContentPane().add(besökartypLabel);
Label beloppLabel_1 = new Label("Belopp");
beloppLabel_1.setBounds(122, 77, 62, 22);
frame.getContentPane().add(beloppLabel_1);
Label tidLabel_1 = new Label("Tid");
tidLabel_1.setBounds(246, 77, 22, 22);
frame.getContentPane().add(tidLabel_1);
Label lopnrLabel = new Label("L\u00F6pnummer");
lopnrLabel.setBounds(345, 77, 79, 22);
frame.getContentPane().add(lopnrLabel);
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Företag");
comboBox.addItem("Normal");
comboBox.addItem("Student");
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int kb = 0;
JComboBox<?> comboBox = (JComboBox<?>) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("Normal")) {
Register r = new Register();
Kund k = new Normal();
k.setBelopp(100);
k.setDatum("20:15");
r.regKund(k);
int tempbelopp = k.getBelopp();
String b = Integer.toString(tempbelopp);
beloppField.setText(b);
kb = kb + 100;
tidField.setText("20:15");
textArea.append(r.getLista());
}
else if(selected.toString().equals("Student")) {
Register r = new Register();
Kund k = new Normal();
k=new Student();
k.setBelopp(50);
k.setDatum("20:16");
beloppField.setText("100");
tidField.setText("20:15");
if( kb >=50)
r.regKund(k);
kb = kb - 50;
textArea.append("Det finns inga cash, student reggades ej!" + "\n");
}
else if(selected.toString().equals("Företag")) {
Register r = new Register();
Kund k = new Normal();
k.setBelopp(0);
k.setDatum("20:17");
k.setLopnummer(r.getLopnummer());
r.regKund(k);
// Den skriver ut samma skit ändra det
textArea.append(r.getLista());
textArea.append("Kassan har nu "+kb+" kr" + "\n");
}
}
});
comboBox.setToolTipText("Välj vilken typ av Kund du är");
comboBox.setRenderer(new MyComboBoxRenderer("Välj..."));
comboBox.setSelectedIndex(-1);
comboBox.setBounds(171, 46, 97, 22);
frame.getContentPane().add(comboBox);
}
}
class MyComboBoxRenderer extends JLabel implements ListCellRenderer<Object> {
private String title;
public MyComboBoxRenderer(String newTitle) {
title = newTitle;
}
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean hasFocus) {
if (index == -1 && value == null) setText(title );
else setText(value.toString());
return this;
}
}
And it gives me error cause of this line comboBox.setSelectedIndex(-1);is there any way to change it. Since what it does it sets the comboBox defult text to "Välj..." (Which means choose in swedish) i would like to keep this without removing it. When i remove that line the program works perfectly.
When setSelectedIndex is called this statement should throw an NPE (not tested)
Object selected = comboBox.getSelectedItem();
since nothing is selected. You could simply move the setSelectedIndex statement before the ActionListener is registered with the combobox
I have 2 classes. One class is for gui and the other class doing some staff.
The second class includes Swingworker. It searches some log files and take some sentence from there. Also in the gui there is a label which writes in Searching.. Please wait.. and when the second class finish the work, it should be changed to Searching is finished.. .
This label name is searchLabeland define in first class. It is private variable.
My purpose is : In the second class there is done method. Inside in this method, I want to do searchLabel.setText("blabla");
How can I do this ? I cannot access. Also doing public JLabel is not a solution I think.
You can easily find that part in the code with searcing /* PROBLEM IS IN HERE */ this string.
Here is the code
This is my gui class :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
public class mainGui extends JFrame {
private JPanel contentPane;
private JTextField userNametextField;
public static JLabel searchLabel,userNameWarningLabel,pathWarningLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainGui frame = new mainGui();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/4;
int y = (dim.height-h)/2;
frame.setLocation(x, y);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 455);
contentPane = new JPanel();
getContentPane().setLayout(null);
setTitle("Role Finding Script");
// Border border;
JLabel lblUsername = new JLabel(" Username :");
lblUsername.setFont(new Font("LucidaSans", Font.BOLD, 13));
lblUsername.setBounds(10, 53, 113, 30);
//Border border = BorderFactory.createRaisedSoftBevelBorder();
// border = BorderFactory.createEtchedBorder();
// lblUsername.setBorder(border);
getContentPane().add(lblUsername);
userNametextField = new JTextField();
userNametextField.setBounds(146, 53, 250, 30);
userNametextField.setFont(new Font("LucidaSans", Font.PLAIN, 13));
getContentPane().add(userNametextField);
userNametextField.setColumns(20);
JLabel lblRole = new JLabel(" Roles :");
lblRole.setFont(new Font("LucidaSans", Font.BOLD, 13));
lblRole.setBounds(10, 124, 113, 30);
// border = BorderFactory.createEtchedBorder();
// lblRole.setBorder(border);
getContentPane().add(lblRole);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setBounds(146, 124, 250, 30);
comboBox.addItem("VR_ANALYST1");
comboBox.addItem("VR_ANALYST2");
comboBox.addItem("VR_ANALYST3");
comboBox.addItem("VR_ANALYST4");
comboBox.addItem("VR_ANALYST5");
comboBox.addItem("VR_ANALYST6");
comboBox.addItem("VR_ANALYST7");
comboBox.addItem("VR_ANALYST8");
comboBox.addItem("VR_ANALYST9");
comboBox.addItem("VR_ANALYST10");
comboBox.addItem("VR_ANALYST11");
comboBox.addItem("VR_ANALYST12");
comboBox.setMaximumRowCount(6);
getContentPane().add(comboBox);
this.searchLabel = new JLabel("Searching.. Please wait..");
searchLabel.setFont(new Font("LucidaSans", Font.BOLD, 13));
searchLabel.setBounds(169, 325, 195, 30);
searchLabel.setVisible(false);
getContentPane().add(searchLabel);
JButton btnNewButton = new JButton("Show Me ");
btnNewButton.setFont(new Font("LucidaSans", Font.BOLD, 13));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(userNametextField.getText() == null || userNametextField.getText().equals("")){
userNameWarningLabel.setText("Please filled in the Username part.");
}else{
searchLabel.setVisible(true);
VolvoMain task = new VolvoMain();
task.execute();
}
}
});
btnNewButton.setBounds(188, 271, 126, 30);
getContentPane().add(btnNewButton);
JLabel lblPath = new JLabel(" Path :");
lblPath.setFont(new Font("Dialog", Font.BOLD, 13));
lblPath.setBounds(10, 195, 113, 30);
getContentPane().add(lblPath);
userNameWarningLabel = new JLabel("");
userNameWarningLabel.setBounds(156, 89, 227, 14);
userNameWarningLabel.setFont(new Font("Dialog", Font.ITALIC, 10));
userNameWarningLabel.setForeground(Color.red);
getContentPane().add(userNameWarningLabel);
JButton btnNewButton_1 = new JButton("...");
btnNewButton_1.setBounds(412, 195, 30, 30);
getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("+");
btnNewButton_2.setBounds(460, 195, 44, 30);
getContentPane().add(btnNewButton_2);
JLabel headerLabel = new JLabel("Find the Role");
headerLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
headerLabel.setHorizontalAlignment(SwingConstants.CENTER);
headerLabel.setBounds(94, 11, 358, 30);
headerLabel.setForeground(Color.red);
getContentPane().add(headerLabel);
pathWarningLabel = new JLabel("");
pathWarningLabel.setForeground(Color.RED);
pathWarningLabel.setFont(new Font("Dialog", Font.ITALIC, 10));
pathWarningLabel.setBounds(156, 236, 227, 14);
getContentPane().add(pathWarningLabel);
}
}
And this is the other class :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.SwingWorker;
public class VolvoMain extends SwingWorker{
private FileInputStream fstream;
private BufferedReader br;
private String username = "HALAA";
private String role = "VR_ANALYST";
private String firstLine = "";
private Pattern regex;
private List<String> stringList = new ArrayList<String>();
private File dir;
private mainGui mg = new mainGui();
//String reg = "\\t'AUR +(" + username + ") .*? /ROLE=\"(" + role + ")\".*$";
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground() throws Exception {
String fmt = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";
String reg = String.format(fmt, username, role);
regex = Pattern.compile(reg);
dir = new File(
"C:"+File.separator+"Documents and Settings"+File.separator+"sbx1807"+File.separator+"Desktop"+File.separator
+"Batu"+File.separator+"Deneme"+File.separator
);
File[] dirs = dir.listFiles();
String[] txtArray = new String[dirs.length];
int z=0;
for (File file : dirs) {
if (file.isDirectory()) {
}else {
if(file.getAbsolutePath().endsWith(".log")){
txtArray[z] = file.getAbsolutePath();
System.out.println(file.getAbsolutePath());
z++;
}
}
int j = 0;
for(int i=0; i<txtArray.length; i++){
if(txtArray[i] != null && !txtArray[i].equals("")){
try{
fstream = new FileInputStream(txtArray[i]);
br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
/* parse strLine to obtain what you want */
if((j%2)== 0){
firstLine = strLine;
}
if(((j%2) != 0) && regex.matcher(strLine).matches()){
stringList.add(firstLine);
stringList.add(strLine);
}
publish(stringList.size());
j++;
}
publish(stringList.size());
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
for(int k=0; k<stringList.size(); k++){
System.out.println(stringList.get(k));
}
}
return null;
}
#Override
public void done() {
System.out.println("bitti");
// getSearchJLabel().setText("Searching is done..");
// mainGui m = new mainGui();
// m.searchLabel.setText("done");
}
}
Adjust your VolvoMain class so it takes a reference to the JLabel in its constructor. Store this in a private final field and you can use this in the done() method.
public class VolvoMain extends SwingWorker{
// ...
private final JLabel labelToUpdate;
public VolvoMain(JLabel labelToUpdate) {
this.labelToUpdate = labelToUpdate;
}
// ...
#Override
public void done() {
// Update labelToUpdate here
}
The done() method will be invoked on the Event Dispatch Thread, so it will be safe to adjust the label text directly.