reading name contact - java

Im making a contact list, and my code compiles and runs, when you add the contact, type or email or phone its supposed to read them to you, the problem I have here is when I add the contacts and press next or previous, first or last it doesnt read the Name Contact, but it reads everything else...does it have to do something with spacing ? here is what I have...thanks
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ContactSystem extends JFrame{
//Specify the size of five string fields in the record
final static int NAME_SIZE = 32;
final static int TYPE_SIZE = 32;
final static int CITY_SIZE = 20;
final static int PHONE_SIZE = 15;
final static int EMAIL_SIZE = 15;
final static int RECORD_SIZE =
(NAME_SIZE + TYPE_SIZE + CITY_SIZE + PHONE_SIZE + EMAIL_SIZE);
//access contact.dat using RandomAccessFile
private RandomAccessFile raf;
//Text Fields
private JTextField jbtName = new JTextField(NAME_SIZE);
private JTextField jbtType = new JTextField(TYPE_SIZE);
private JTextField jbtCity = new JTextField(CITY_SIZE);
private JTextField jbtPhone = new JTextField(PHONE_SIZE);
private JTextField jbtEmail = new JTextField(EMAIL_SIZE);
//Buttons
private JButton jbtAdd = new JButton("Add");
private JButton jbtFirst = new JButton("First");
private JButton jbtNext = new JButton("Next");
private JButton jbtPrevious = new JButton("Previous");
private JButton jbtLast = new JButton("Last");
public ContactSystem(){
//open or create a random access file
try {
raf = new RandomAccessFile("contact.txt", "rw");
}
catch(IOException ex) {
System.out.print("Error: " + ex);
System.exit(0);
}
//Panel p1 for holding labels Name , Type, Email or phone
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3,1));
p1.add(new JLabel("Name Contact"));
p1.add(new JLabel("Email Address"));
p1.add(new JLabel("Type of Contact"));
//Panel jpPhone for holding Phone
JPanel jpPhone = new JPanel();
jpPhone.setLayout(new BorderLayout());
jpPhone.add(new JLabel("Phone"), BorderLayout.WEST);
jpPhone.add(jbtPhone, BorderLayout.CENTER);
//Panel jpEmail for holding Phone
JPanel jpEmail = new JPanel();
jpEmail.setLayout(new BorderLayout());
jpEmail.add(new JLabel("Phone"), BorderLayout.WEST);
jpEmail.add(jbtEmail, BorderLayout.CENTER);
// Panel p2 for holding jpPhone and jpEmail
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(jpPhone, BorderLayout.WEST);
p2.add(jpPhone, BorderLayout.CENTER);
JPanel p3 = new JPanel();
p3.setLayout(new BorderLayout());
p3.add(jbtCity, BorderLayout.CENTER);
p3.add(p2, BorderLayout.EAST);
//panel p4 for holding jtfName, jtfType, and p3
JPanel p4 = new JPanel();
p4.setLayout(new GridLayout(3,1));
p4.add(jbtName);
p4.add(jbtType);
p4.add(p3);
//place p1 and p4 into jpContact
JPanel jpContact = new JPanel(new BorderLayout());
jpContact.add(p1, BorderLayout.WEST);
jpContact.add(p4, BorderLayout.CENTER);
//set panel with line border
jpContact.setBorder(new BevelBorder(BevelBorder.RAISED));
//add buttons to a panel
JPanel jpButton = new JPanel();
jpButton.add(jbtAdd);
jpButton.add(jbtFirst);
jpButton.add(jbtNext);
jpButton.add(jbtPrevious);
jpButton.add(jbtLast);
//add jpContact and jpButton to the frame
add(jpContact, BorderLayout.CENTER);
add(jpButton, BorderLayout.SOUTH);
jbtAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writeContact();
}
});
jbtFirst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (raf.length() > 0) readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtNext.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if (currentPosition < raf.length())
readContact(currentPosition);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
jbtPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if(currentPosition - 2 * RECORD_SIZE > 0)
//why 2 * 2 * RECORD_SIZE? see the the follow-up remarks
readContact(currentPosition - 2 * 2 * RECORD_SIZE);
else
readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long lastPosition = raf.length();
if(lastPosition > 0)
//why 2 * RECORD_SIZE? see the follow up remarks
readContact(lastPosition - 2 * RECORD_SIZE);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
try {
if (raf.length() > 0) readContact(0);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//write a record at the end of file
public void writeContact() {
try {
raf.seek(raf.length());
FixedLengthStringIO.writeFixedLengthString(
jbtName.getText(), NAME_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtType.getText(), TYPE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtCity.getText(), CITY_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtPhone.getText(), PHONE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtEmail.getText(), EMAIL_SIZE, raf);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//read a contact at the specific position
public void readContact(long position) throws IOException{
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtName.setText(phone);
jbtName.setText(email);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ContactSystem frame = new ContactSystem();
frame.pack();
frame.setTitle("Contact System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
fixedlengthstringIO class
import java.io.*;
public class FixedLengthStringIO {
//read fixed number of characters from datainput stream
public static String readFixedLengthString(int size,
DataInput in) throws IOException {
//declare an array of characters
char[] chars = new char[size];
//read fixed number of characters to the array
for(int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String (chars);
}
//write fixed number of characters to a dataoutput stream
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException {
char[] chars = new char[size];
//fill an array of characters from the string
s.getChars(0, Math.min(s.length(), size), chars, 0);
//fill in blank characters in the rest of the array
for (int i = Math.min(s.length(), size); i < chars.length; i++)
chars[i] = ' ';
//create and write a new string padded with blank characters
out.writeChars(new String(chars));
}
}
here is when I type in contact name, type, email etc into the list
and when I press next or previous, or first or last, it doesnt read the name..

Glitch is in your readContact method, change this
public void readContact(long position) throws IOException {
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtPhone.setText(phone);
jbtEmail.setText(email);
}
Also instead of adding separate ActionListner command button you can implement like
public class ContactSystem extends JFrame implements ActionListener
{
.....
jbtAdd.addActionListener(this);
jbtFirst.addActionListener(this);
.....
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Add")) {
//do add stuff
} else if (actionCommand.equals("First")) {
// move first
}
}
}

Related

Trying to export project as Runnable Jar file

Below is my full code, it compiles properly within the eclipse IDE, but when I try and export it as a runnable JAR file, it says it exported with errors. Then When I try to run the Jar file, none of the labels or text fields show up, nor does my event handler on the button work. I'm not sure what to change since it compiled properly before it was exported.
public class TaskFrame extends JFrame implements ActionListener {
private JPanel taskPanel, buttonPanel, viewPanel, titlePanel;
private JButton editButton;
private String[] labelNames = {"Notes", "Paging", "Event Mgmt - Early", "Event Mgmt - Late", "Airhub 2DA",
"Airhub 1DA", "GSSD", "GSSI", "GSSRR", "Holdovers", "Radio", "PTI", "Phones 1300", "Publishing"};
private JLabel[] labelArray = new JLabel[labelNames.length];
private JLabel titleLabel = new JLabel("Task Dashboard");
private JTextField[] textArray = new JTextField[labelNames.length];
private String[] namesArray = new String[labelNames.length];
private Font titleFont = new Font("Helvetica", Font.BOLD, 24);
private Color backgroundColor = new Color(255,250,245);
#Override
public void actionPerformed(ActionEvent arg0) {
}
public static void main(String[] args) {
TaskFrame frame = new TaskFrame();
frame.setTitle("Task List");
frame.setSize(300, 450);
frame.setResizable(false);
frame.setVisible(true);
}
public TaskFrame() {
//Create the locked task panel
taskPanel = new JPanel(new GridLayout(14,2,1,2));
buttonPanel = new JPanel(new FlowLayout());
titlePanel = new JPanel(new FlowLayout());
titleLabel.setFont(titleFont);
titlePanel.add(titleLabel, SwingConstants.CENTER);
viewPanel = new JPanel(new FlowLayout());
//create the button object and assign the event handler
editButton = new JButton("Edit Tasks");
editButton.setPreferredSize(new Dimension(100,25));
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!textArray[0].isEditable()) {
for(int i = 0; i < labelNames.length; i++) {
textArray[i].setEditable(true);
}
editButton.setText("Save Tasks");
} else {
try {
PrintWriter writeNames = new PrintWriter("Techs.txt", "UTF-8");
for(int i = 0; i < labelNames.length; i ++) {
writeNames.println(textArray[i].getText());
textArray[i].setEditable(false);
}
writeNames.close();
} catch (FileNotFoundException e1) {
e1.getMessage();
} catch (UnsupportedEncodingException e1) {
e1.getMessage();
}
}
}
});
buttonPanel.add(editButton);
//Loop to create all the viewPanel objects, JLabels and JTextFields
try {
FileReader fr = new FileReader("Techs.txt");
BufferedReader br = new BufferedReader(fr);
for(int i = 0; i < labelNames.length; i++) {
labelArray[i] = new JLabel(labelNames[i] + ": ", SwingConstants.LEFT);
textArray[i] = new JTextField(10);
namesArray[i] = new String();
namesArray[i] = br.readLine();
textArray[i].setText(namesArray[i]);
textArray[i].setEditable(false);
taskPanel.add(labelArray[i]);
taskPanel.add(textArray[i]);
}
} catch (FileNotFoundException e1) {
e1.getMessage();
} catch (IOException e1) {
e1.getMessage();
}
//Assign the defined background color to all panels
titlePanel.setBackground(backgroundColor);
taskPanel.setBackground(backgroundColor);
buttonPanel.setBackground(backgroundColor);
viewPanel.setBackground(backgroundColor);
viewPanel.add(titlePanel, BorderLayout.NORTH);
viewPanel.add(taskPanel, BorderLayout.CENTER);
viewPanel.add(buttonPanel, BorderLayout.SOUTH);
add(viewPanel);
viewPanel.setVisible(true);
}
}

drawing a graph using an updating JSlider

I'm making a grapher that draws a graph from a mathematical expression given by user .additionally the program has a slider and play button that user can choose a variable for the slider and its range so upon clicking the play button the slider will start from minimum range to maximum and the graph will be drawn.
for the timer I'm using the answer from a previous question.
for the grapher I'm using This code. (I'm working specifically on Plotter.java file)
The edited Plotter.java file with the playable slider(timer) code :
import java.util.*;
public class Plotter extends JFrame implements ActionListener
{
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem openMenuItem = new JMenuItem("Open");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private int value;
private JComboBox eqCombo = new JComboBox();
private JButton addButton, removeButton, clearButton ;
private Graph graph;
private JPanel userPanel , sliderPanel;
private JSlider slider_1 = new JSlider();
private JButton playButton = new JButton();
private JTextField textField = new JTextField();
private Timer timer ;
private ImageIcon playIcon = new ImageIcon(getClass().getResource("/images/play.png"));
private ImageIcon pauseIcon = new ImageIcon(getClass().getResource("/images/pause.png"));
public Plotter(double lowX, double highX, double frequency, String file) throws GraphArgumentsException, IOException
{
super("Plotter");
textField.setBounds(266, 11, 134, 28);
textField.setColumns(10);
createNewGraph(lowX, highX, frequency, file);
createLayout();
//createsliderpanel();
}
private void createLayout() throws GraphArgumentsException
{
Container c = getContentPane();
setSize(850,600);
getContentPane().setLayout(null);
c.add(graph);
c.add(userPanel);
JPanel down = new JPanel();
down.setBounds(0, 437, 650, 119);
getContentPane().add(down);
down.setLayout(null);
slider_1.setValue(0);
slider_1.setMajorTickSpacing(5);
slider_1.setMinorTickSpacing(1);
slider_1.setPaintLabels(true);
slider_1.setPaintTicks(true);
slider_1.setBounds(145, 51, 467, 42);
down.add(slider_1);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
playButton.setBounds(16, 51, 117, 29);
playButton.setIcon(playIcon);
down.add(playButton);
down.add(textField);
JPanel panel_1 = new JPanel();
panel_1.setBounds(649, 39, 201, 517);
getContentPane().add(panel_1);
panel_1.setLayout(new BorderLayout(0, 0));
// c.add(sliderPanel , BorderLayout.SOUTH);
createMenuBar();
}
/**
* Creates a new Graph instance and adds equations from file into Graph
* #param eqFile file where equations are stored
* #throws IOException
*/
private void createNewGraph(double minX, double maxX, double freq, String eqFile) throws GraphArgumentsException, IOException
{
Equation[] eq = null;
graph = new Graph(minX, maxX, freq);
graph.setBounds(0, 39, 650, 396);
eq = readEquationsFromFile(eqFile);
if (eq != null)
addEquation(eq);
graph.setBackground(Color.WHITE);
userPanel = createUserPanel(eq);
}
private void createMenuBar()
{
menuBar.add(fileMenu);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
openMenuItem.addActionListener(this);
saveMenuItem.addActionListener(this);
exitMenuItem.addActionListener(this);
setJMenuBar(menuBar);
}
/**
* Create user panel at top of the GUI for adding and editing functions
* #param eq equation list to add into the combo box
* #return panel containing buttons and an editable combo box
*/
private JPanel createUserPanel(Equation[] eq)
{
JPanel up = new JPanel(new FlowLayout(FlowLayout.LEFT));
up.setBounds(0, 0, 844, 39);
eqCombo.setEditable(true);
if (eq != null)
{
//Add all equations into the combo box
for (int i = 0; i < eq.length; i++)
eqCombo.addItem(eq[i].getPrefix());
}
addButton = new JButton("Add");
removeButton = new JButton("Remove");
clearButton = new JButton("Clear");
addButton.addActionListener(this);
removeButton.addActionListener(this);
clearButton.addActionListener(this);
up.add(eqCombo);
up.add(addButton);
up.add(removeButton);
up.add(clearButton);
return up;
}
// slider panel
/*private JPanel createsliderpanel()
{
JPanel down = new JPanel(new FlowLayout(FlowLayout.LEFT));
playbutton = new JButton("Play");
slider = new JSlider();
field = new JTextField();
down.add(playbutton);
down.add(slider);
down.add(field);
return down;
}*/
/**
* Check action lister for button and menu events
*/
public void actionPerformed(ActionEvent e)
{
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int value = slider_1.getValue() + 1;
if (value >= slider_1.getMaximum()) {
stopTheClock();
} else {
slider_1.setValue(value);
}
}
});
slider_1.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
textField.setText(Integer.toString(slider_1.getValue()));
}
});
slider_1.setValue(0);
playButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
stopTheClock();
} else {
startTheClock();
}
}
});
if (e.getSource() == addButton)
addEquation((String)eqCombo.getSelectedItem());
else if (e.getSource() == removeButton)
removeEquation(eqCombo.getSelectedIndex());
else if (e.getSource() == saveMenuItem)
saveEquationList();
else if (e.getSource() == openMenuItem)
loadEquations();
else if (e.getSource() == clearButton)
clearEquations();
else if (e.getSource() == exitMenuItem)
System.exit(0);
}
/**
* Save equations to file
*
*/
private void saveEquationList()
{
try
{
PrintWriter out = new PrintWriter(new FileWriter("myeq.txt"));
for (int i = 0; i < eqCombo.getItemCount(); i++)
out.println(eqCombo.getItemAt(i));
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
private void clearEquations()
{
graph.removeAllEquations();
eqCombo.removeAllItems();
}
/**
* Load equations from file into graph
*
*/
private void loadEquations()
{
String file=null;
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(null);
if (fc.getSelectedFile() != null)
{
file = fc.getSelectedFile().getPath();
try
{
Equation[] eq = readEquationsFromFile(file);
if (eq != null)
{
clearEquations();
addEquation(eq);
//Restock combo box with new equations
for (int i = 0; i < eq.length; i++)
eqCombo.addItem(eq[i].getPrefix());
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "ERR4: Unable to read or access file", "alert", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Add an equation to the Graph
* #param eq equation
*/
private void addEquation(String eq)
{
try
{
if (eq != null && !eq.equals(""))
{
Equation equation = new Equation(eq);
eqCombo.addItem(eq);
graph.addEquation(equation);
}
}
catch (EquationSyntaxException e)
{
JOptionPane.showMessageDialog(null, "ERR2: Equation is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Add multiple equations to Graph
* #param eq equation array
*/
private void addEquation(Equation[] eq)
{
for (int i = 0; i < eq.length; i++)
{
graph.addEquation(eq[i]);
}
}
/**
* Remove equation from Graph
* #param index index to remove
*/
private void removeEquation(int index)
{
if (index >= 0)
{
graph.removeEquation(index);
eqCombo.removeItem(eqCombo.getSelectedItem());
}
}
// Timer methods
protected void startTheClock() {
slider_1.setValue(0);
timer.start();
playButton.setIcon(pauseIcon);;
}
protected void stopTheClock() {
timer.stop();
playButton.setIcon(playIcon);
}
/**
* Read file and extract equations into an array. Any errors on an equation halt the loading of the entire file
* #param file name of file containing equations
* #return array of equations
* #throws IOException
*/
public Equation[] readEquationsFromFile(String file) throws IOException
{
ArrayList<Equation> eqList = new ArrayList<Equation>(20);
if (file == null)
return null;
String line;
int lineCount = 1;
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null)
{
Equation eq = new Equation(line);
eqList.add(eq);
lineCount++;
}
br.close();
return ((Equation[])(eqList.toArray(new Equation[0])));
}
catch (EquationSyntaxException e)
{
JOptionPane.showMessageDialog(null, "ERR2.1: Equation on line " + lineCount + " is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
return null;
}
}
/**
* Set up Plotter object and draw the graph.
* #param args command line arguments for Plotter
*/
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String expr = JOptionPane.showInputDialog("Enter your expression");
String maxInput = JOptionPane.showInputDialog("Enter max value of x");
String minInput = JOptionPane.showInputDialog("Enter min value of x");
double frequency = 0.01;
double maxX = Double.parseDouble(maxInput);
double minX = Double.parseDouble(minInput);
String eqFile = null;
try
{
///double minX = Double.parseDouble(args[0]);
// double maxX = Double.parseDouble(args[1]);
// double frequency = Double.parseDouble(args[2]);
//double minX = -10;
//double maxX = 10;
//double frequency = 0.01;
if (args.length > 3)
eqFile = args[3];
Plotter plotterGUI = new Plotter(minX, maxX, frequency, eqFile);
plotterGUI.setVisible(true);
plotterGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch (NumberFormatException e)
{
System.out.println("ERR: Invalid arguments");
}
catch (GraphArgumentsException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.print("ERR4: Unable to read or access file");
}
}
}
general look of program :
now I want to change the code so the slider will affect the grapher .it means when user chooses the range of x from -10 to 10 , by clicking the play button the grapher starts to draw the graph as slider changes the x from -10 to 10
Gapminder chart is an example about slider and grapher should work.
The question is how can I do this ?
here is a small code which might help you get the insight of JSlider.
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class demo extends JFrame
{
JFrame f=new JFrame("G");
JSlider slide=new JSlider();
JTextField field=new JTextField();
JTextField d=new JTextField();
final double value=0;
demo()
{
setSize(500,500);
f.setSize(600,600);
f.setVisible(true);
slide.setBounds(100,100,200,50);
field.setBounds(150,150,100,30);
d.setBounds(0,0,0,0);
add(slide);
add(field);
add(d);
}
public static void main(String args[])
{
demo m=new demo();
m.setVisible(true);
m.setLocationRelativeTo(null);
m.slidec();
}
public double slidec()
{
slide.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
double value=((JSlider)e.getSource()).getValue();
field.setText(Double.toString(value));
}
});
return value;
}
}

Why Windows doesn't show the same output for ImageIcon on JButton as Ubuntu?

I am trying to make an image gallery just like in the following image but Windows shows images' unnecessary background whereas in Ubuntu it shows correctly.
I use the following code...
public class CommonGalleryPanel extends JPanel implements ActionListener {
public static boolean isGallaryAllowed = false;
private int counter = 0;
private InputStream binaryStream;
private BufferedImage img;
private ImageIcon iconImg;
private JButton[] btns;
private JCheckBox[] checkBox;
private JButton nextButton;
private JButton prevButton;
private ResultSet rs;
private String imageID;
private long lastRecordWas;
private long selectedOrnamentType;
private JPanel[] panels;
private JButton okButton;
private JPanel centerPanel;
private JPanel eastPanel;
private JPanel northPanel;
private JPanel southPanel;
private JComboBox<String> itemsCombo;
private String[] itemsList;
private JButton load;
private JPanel westPanel;
private int rsLen = 0;
private int noOfRows;
private BufferedImage nextButtonImage;
private BufferedImage prevButtonImage;
private static List<Long> listOfSelectedOrnaments;
private Administrator admin;
public static List<Long> getListOfSelectedOrnaments() {
return listOfSelectedOrnaments;
}
public static void setListOfSelectedOrnaments(
List<Long> listOfSelectedOrnaments) {
CommonGalleryPanel.listOfSelectedOrnaments = listOfSelectedOrnaments;
}
public CommonGalleryPanel(Administrator admin) {
this.admin = admin;
try {
setLayout(new BorderLayout());
centerPanel = new JPanel(new FlowLayout());
eastPanel = new JPanel(new GridLayout());
westPanel = new JPanel(new GridLayout());
northPanel = new JPanel(new GridBagLayout());
southPanel = new JPanel(new GridBagLayout());
listOfSelectedOrnaments = new ArrayList<Long>();
itemsList = DatabaseHandler.getOrnamentTypesInString();
itemsCombo = new JComboBox<String>(itemsList);
load = new JButton("Load");
load.addActionListener(this);
load.setActionCommand("loadButton");
northPanel.setBackground(Color.LIGHT_GRAY);
eastPanel.setBackground(Color.LIGHT_GRAY);
westPanel.setBackground(Color.LIGHT_GRAY);
southPanel.setBackground(Color.LIGHT_GRAY);
centerPanel.setBackground(Color.GRAY);
northPanel.add(itemsCombo);
northPanel.add(new JLabel(" "));
northPanel.add(load);
northPanel.add(Box.createRigidArea(new Dimension(0, 50)));
add(northPanel, BorderLayout.NORTH);
try {
nextButtonImage = Utility
.getMyResource("/buttons/next-btn.png");
prevButtonImage = Utility.getMyResource("/buttons/pre-btn.png");
} catch (Exception ex) {
ex.printStackTrace();
}
prevButton = new JButton(new ImageIcon(
prevButtonImage.getScaledInstance(40, 100,
BufferedImage.SCALE_AREA_AVERAGING)));
prevButton.setSize(getMaximumSize());
westPanel.add(prevButton);
add(eastPanel, BorderLayout.EAST);
nextButton = new JButton(new ImageIcon(
nextButtonImage.getScaledInstance(40, 100,
BufferedImage.SCALE_AREA_AVERAGING)));
eastPanel.add(nextButton);
add(westPanel, BorderLayout.WEST);
okButton = new JButton("Demonstrate");
southPanel.add(Box.createRigidArea(new Dimension(0, 50)));
southPanel.add(okButton);
add(southPanel, BorderLayout.SOUTH);
add(centerPanel, BorderLayout.CENTER);
repaint();
revalidate();
setVisible(true);
nextButton.addActionListener(this);
okButton.addActionListener(this);
prevButton.addActionListener(this);
nextButton.setActionCommand("nextButton");
okButton.setActionCommand("okButton");
prevButton.setActionCommand("prevButton");
revalidate();
repaint();
setVisible(true);
} catch (Exception backException) {
backException.printStackTrace();
}
}
public void getImages(ResultSet rs) {
try {
rsLen = 0;
while (rs.next()) {
counter++;
rsLen++;
}
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
noOfRows = DatabaseHandler
.getRowCountOfGivenSubOrnamentType(selectedOrnamentType);
} else {
noOfRows = DatabaseHandler
.getRowCountOfGivenOrnamentType(selectedOrnamentType);
}
checkBox = new JCheckBox[noOfRows + 1];
List<String> listOfImageIds = new ArrayList<String>(counter);
rs.beforeFirst();
while (rs.next()) {
listOfImageIds.add(rs.getString(1));
}
rs.beforeFirst();
int i = 0;
centerPanel.removeAll();
btns = new JButton[10];
panels = new JPanel[10];
while (rs.next()) {
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
binaryStream = rs.getBinaryStream(2);
} else {
binaryStream = rs.getBinaryStream(2);
}
img = ImageIO.read(binaryStream);
iconImg = new ImageIcon(img.getScaledInstance(290, 180,
BufferedImage.TYPE_INT_ARGB));
btns[i] = new JButton(iconImg);
checkBox[i] = new JCheckBox();
checkBox[i].setActionCommand(String.valueOf(rs.getLong(1)));
panels[i] = new JPanel();
btns[i].setBorderPainted(false);
btns[i].setActionCommand(String.valueOf(rs.getLong(1)));
btns[i].setBackground(new Color(0, 0, 0, 0));
btns[i].addActionListener(this);
//btns[i].setOpaque(true);
panels[i].add(btns[i]);
panels[i].add(checkBox[i]);
panels[i].setBackground(Color.LIGHT_GRAY);
centerPanel.add(panels[i]);
lastRecordWas = rs.getLong(1);
System.out.println("lastRecordWas = " + lastRecordWas);
i++;
}
for (int j = 0; j < i; j++) {
final int k = j;
checkBox[j].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (checkBox[k].isSelected()) {
System.out.println("Selected image..."
+ checkBox[k].getActionCommand());
listOfSelectedOrnaments.add(Long
.parseLong(checkBox[k].getActionCommand()));
} else {
System.out.println("Deselected image..."
+ checkBox[k].getActionCommand());
listOfSelectedOrnaments.remove(Long
.parseLong(checkBox[k].getActionCommand()));
}
System.out.println("Selected items list = "
+ listOfSelectedOrnaments);
}
});
}
System.out.println("counter = " + counter);
if (rsLen == 0) {
centerPanel.add(new JLabel("No more images available...."),
BorderLayout.CENTER);
repaint();
revalidate();
}
} catch (SQLException | IOException ex) {
ex.printStackTrace();
}
add(centerPanel, BorderLayout.CENTER);
repaint();
revalidate();
setVisible(true);
}
public String getImageID() {
return imageID;
}
public void setImageID(String imageID) {
this.imageID = imageID;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("nextButton")) {
System.out.println("next button clicked...");
rs = DatabaseHandler.getNext9ItemsByType(lastRecordWas,
selectedOrnamentType);
getImages(rs);
revalidate();
repaint();
} else if (e.getActionCommand().equals("prevButton")) {
System.out.println("prev button clicked...");
rs = DatabaseHandler.getPrev9ItemsByType(lastRecordWas,
selectedOrnamentType);
getImages(rs);
revalidate();
repaint();
} else if (e.getActionCommand().equals("okButton")) {
try {
if (listOfSelectedOrnaments.isEmpty()) {
JOptionPane
.showMessageDialog(null,
"Please Select at least any one ornament to demonstrate...");
} else {
this.admin.setListOfSelectedOrnaments(
listOfSelectedOrnaments, selectedOrnamentType);
System.out.println("list is setteled with Selected images "
+ listOfSelectedOrnaments);
this.setVisible(false);
}
} catch (Exception ee) {
ee.printStackTrace();
}
} else if (e.getActionCommand().equals("loadButton")) {
try {
this.selectedOrnamentType = DatabaseHandler
.getOrnamentIdFromOrnamentName(itemsCombo
.getSelectedItem().toString());
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
rs = DatabaseHandler.getNext9EaringsByType(0l,
this.selectedOrnamentType);
} else {
rs = DatabaseHandler.getNext9ItemsByType(0l,
this.selectedOrnamentType);
}
getImages(rs);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
try {
System.out.println("Selected image = " + e.getActionCommand());
ImageViewer.showImage(Long.parseLong(e.getActionCommand()),itemsCombo.getSelectedItem().toString());
setImageID(e.getActionCommand());
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
}
Basically it works well with Ubuntu then why not on Windows ?
Just a suggestion:
put this lines first in your Main-Method:
public static void main(String[] args)
{
String propertyName = "sun.java2d.noddraw";
System.setProperty(propertyName, "true");
propertyName = "sun.java2d.d3d";
System.setProperty(propertyName, "false");
//YOUR CODE HERE...
}
By doing this, you will TURN OFF usage of direct3D and directDraw.
You can also try to use a different LookAndFeel: (here as example MetalLookAndFeel)
public static void main(String[] args)
{
String propertyName = "sun.java2d.noddraw";
System.setProperty(propertyName, "true");
propertyName = "sun.java2d.d3d";
System.setProperty(propertyName, "false");
try
{
javax.swing.UIManager.setLookAndFeel(MetalLookAndFeel.class.getName());
}
catch (Exception ex)
{
ex.printStackTrace();
}
//YOUR CODE HERE...
}
By default, SystemLookAndFeel will return "WindowsLookAndFeel" (when using Windows)
but on Linux it will return MetalLookAndFeel (or GTKLookAndFeel).
To force Windows to use MetalLookAndFeel (instead of SystemLookAndFeel (which is WindowsLookAndFeel)), you have to use the code above!

Java: Components disappearing after event

I'm trying to make something for fun and my components keep disappearing after I press the "ok" button in my gui.
I'm trying to make a "Guess a word" program, where one will get a tip and you can then enter a guess and if it matches it will give you a message and if not, another tip. The problem is, if you enter something that's not the word it will give you a message that it's not the correct word and it will then give you another tip. But the other tip won't show up. They disappear.
I've two classes, "StartUp" and "QuizLogic".
The problem arrives somewhere in the "showTips" method (I think).
If someone would try it themselves a link to the file can be found here: Link to file
Thank you.
public class StartUp {
private JFrame frame;
private JButton showRulesYesButton;
private JButton showRulesNoButton;
private JButton checkButton;
private JPanel mainBackgroundManager;
private JTextField guessEntery;
private QuizLogic quizLogic;
private ArrayList<String> tips;
private JLabel firstTipLabel;
private JLabel secondTipLabel;
private JLabel thirdTipLabel;
// CONSTRUCTOR
public StartUp() {
// Show "Start Up" message
JOptionPane.showMessageDialog(null, "Guess a Word!");
showRules();
}
// METHODS
public void showRules() {
// Basic frame methods
frame = new JFrame("Rules");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(500, 500));
frame.setLocationRelativeTo(null);
// Creates JLabels and adds to JPanel
JLabel firstRule = new JLabel("1. You will get one tip at a time of what the word could be.");
JLabel secoundRule = new JLabel("2. You will get three tips and unlimited guesses.");
JLabel thirdRule = new JLabel("3. Every word is a noun and in its basic form.");
JLabel understand = new JLabel("Are you ready?");
// Creates JPanel and adds JLabels to JPanel
JPanel temporaryRulesPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 100, 60));
temporaryRulesPanel.add(firstRule);
temporaryRulesPanel.add(secoundRule);
temporaryRulesPanel.add(thirdRule);
temporaryRulesPanel.add(understand);
// Initialize buttons
showRulesYesButton = new JButton("Yes");
showRulesNoButton = new JButton("No");
showRulesYesButton.addActionListener(new StartUpEventHandler());
showRulesNoButton.addActionListener(new StartUpEventHandler());
// Creates JPanel and adds button to JPanel
JPanel temporaryButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 100, 35));
temporaryButtonPanel.add(showRulesYesButton);
temporaryButtonPanel.add(showRulesNoButton);
// Initialize and adds JPanel to JPanel
mainBackgroundManager = new JPanel(new BorderLayout());
mainBackgroundManager.add(temporaryRulesPanel, BorderLayout.CENTER);
mainBackgroundManager.add(temporaryButtonPanel, BorderLayout.SOUTH);
//Adds JPanel to JFrame
frame.add(mainBackgroundManager);
frame.setVisible(true);
}
public void clearBackground() {
mainBackgroundManager.removeAll();
quizLogic = new QuizLogic();
showGuessFrame();
showTips();
}
public void showGuessFrame() {
JPanel guessPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 10));
firstTipLabel = new JLabel("a");
secondTipLabel = new JLabel("b");
thirdTipLabel = new JLabel("c");
tips = new ArrayList<String>();
guessEntery = new JTextField("Enter guess here", 20);
checkButton = new JButton("Ok");
checkButton.addActionListener(new StartUpEventHandler());
guessPanel.add(guessEntery);
guessPanel.add(checkButton);
mainBackgroundManager.add(guessPanel, BorderLayout.SOUTH);
frame.add(mainBackgroundManager);
}
public void showTips() {
JPanel temporaryTipsPanel = new JPanel(new GridLayout(3, 1));
temporaryTipsPanel.removeAll();
tips.add(quizLogic.getTip());
System.out.println(tips.size());
if (tips.size() == 1) {
firstTipLabel.setText(tips.get(0));
}
if (tips.size() == 2) {
secondTipLabel.setText(tips.get(1));
}
if (tips.size() == 3) {
thirdTipLabel.setText(tips.get(2));
}
temporaryTipsPanel.add(firstTipLabel);
temporaryTipsPanel.add(secondTipLabel);
temporaryTipsPanel.add(thirdTipLabel);
mainBackgroundManager.add(temporaryTipsPanel, BorderLayout.CENTER);
frame.add(mainBackgroundManager);
frame.revalidate();
frame.repaint();
}
public void getGuess() {
String temp = guessEntery.getText();
boolean correctAnswer = quizLogic.checkGuess(guessEntery.getText());
if (correctAnswer == true) {
JOptionPane.showMessageDialog(null, "Good Job! The word was " + temp);
}
else {
JOptionPane.showMessageDialog(null, temp + " is not the word we are looking for");
showTips();
}
}
private class StartUpEventHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == showRulesYesButton) {
clearBackground();
}
else if (event.getSource() == showRulesNoButton) {
JOptionPane.showMessageDialog(null, "Read the rules again");
}
else if (event.getSource() == checkButton) {
getGuess();
}
}
}
}
public class QuizLogic {
private ArrayList<String> quizWord;
private ArrayList<String> tipsList;
private int tipsNumber;
private String word;
public QuizLogic() {
tipsNumber = 0;
quizWord = new ArrayList<String>();
quizWord.add("Burger");
try {
loadTips(getWord());
} catch (Exception e) {
System.out.println(e);
}
}
public String getWord() {
Random randomGen = new Random();
return quizWord.get(randomGen.nextInt(quizWord.size()));
}
public void loadTips(String word) throws FileNotFoundException {
Scanner lineScanner = new Scanner(new File("C:\\Users\\Oliver Nielsen\\Dropbox\\EclipseWorkspaces\\BuildingJava\\GuessAWord\\src\\domain\\" + word + ".txt"));
this.word = word;
tipsList = new ArrayList<String>();
while (lineScanner.hasNext()) {
tipsList.add(lineScanner.nextLine());
}
}
public String getTip() {
if (tipsNumber >= tipsList.size()) {
throw new NoSuchElementException();
}
String temp = tipsList.get(tipsNumber);
tipsNumber++;
System.out.println(temp);
return temp;
}
public boolean checkGuess(String guess) {
return guess.equalsIgnoreCase(word);
}
}
I figured it out!
I don't know why it can't be done but if I deleted this line: JPanel temporaryTipsPanel = new JPanel(new GridLayout(3, 1));
and placed it in another method it worked. If someone could explain why that would be great but at least I/we know what was the problem.
Thank you. :)

Update JLabel every X seconds from ArrayList<List> - Java

I have a simple Java program that reads in a text file, splits it by " " (spaces), displays the first word, waits 2 seconds, displays the next... etc... I would like to do this in Spring or some other GUI.
Any suggestions on how I can easily update the words with spring? Iterate through my list and somehow use setText();
I am not having any luck. I am using this method to print my words out in the consol and added the JFrame to it... Works great in the consol, but puts out endless jframe. I found most of it online.
private void printWords() {
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel(w.name,SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
I have a window that get's created with JFrame and JLable, however, I would like to have the static text be dynamic instead of loading a new spring window. I would like it to flash a word, disappear, flash a word disappear.
Any suggestions on how to update the JLabel? Something with repaint()? I am drawing a blank.
Thanks!
UPDATE:
With the help from the kind folks below, I have gotten it to print correctly to the console. Here is my Print Method:
private void printWords() {
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
However, it isn't updating the lable? My contructor looks like:
public TimeThis() {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
//_textField.setText("loading...");
}
Getting there... I'll post the fix once I, or whomever assists me, get's it working. Thanks again!
First, build and display your GUI. Once the GUI is displayed, use a javax.swing.Timer to update the GUI every 500 millis:
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
private Iterator<Word> it = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (it.hasNext()) {
label.setText(it.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
Never use Thread.sleep(int) inside Swing Code, because it blocks the EDT; more here,
The result of using Thread.sleep(int) is this:
When Thread.sleep(int) ends
Example code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
public class ButtonsIcon extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private Queue<Icon> iconQueue = new LinkedList<Icon>();
private JLabel label = new JLabel();
private Random random = new Random();
private JPanel buttonPanel = new JPanel();
private JPanel labelPanel = new JPanel();
private Timer backTtimer;
private Timer labelTimer;
private JLabel one = new JLabel("one");
private JLabel two = new JLabel("two");
private JLabel three = new JLabel("three");
private final String[] petStrings = {"Bird", "Cat", "Dog",
"Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
private boolean runProcess = true;
private int index = 1;
private int index1 = 1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ButtonsIcon t = new ButtonsIcon();
}
});
}
public ButtonsIcon() {
iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));
one.setFont(new Font("Dialog", Font.BOLD, 24));
one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
two.setFont(new Font("Dialog", Font.BOLD, 24));
two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
three.setFont(new Font("Dialog", Font.BOLD, 10));
three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelPanel.setLayout(new GridLayout(0, 3, 4, 4));
labelPanel.add(one);
labelPanel.add(two);
labelPanel.add(three);
//labelPanel.setBorder(new LineBorder(Color.black, 1));
labelPanel.setOpaque(false);
JButton button0 = createButton();
JButton button1 = createButton();
JButton button2 = createButton();
JButton button3 = createButton();
buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
buttonPanel.add(button0);
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
//buttonPanel.setBorder(new LineBorder(Color.black, 1));
buttonPanel.setOpaque(false);
label.setLayout(new BorderLayout());
label.add(labelPanel, BorderLayout.NORTH);
label.add(buttonPanel, BorderLayout.SOUTH);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));
add(label, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
startBackground();
startLabel2();
new Thread(this).start();
printWords(); // generating freeze Swing GUI durring EDT
}
private JButton createButton() {
JButton button = new JButton();
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setIcon(nextIcon());
button.setRolloverIcon(nextIcon());
button.setPressedIcon(nextIcon());
button.setDisabledIcon(nextIcon());
nextIcon();
return button;
}
private Icon nextIcon() {
Icon icon = iconQueue.peek();
iconQueue.add(iconQueue.remove());
return icon;
}
// Update background at 4/3 Hz
private void startBackground() {
backTtimer = new javax.swing.Timer(750, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private Action updateBackground() {
return new AbstractAction("Background action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
// Update Label two at 2 Hz
private void startLabel2() {
labelTimer = new javax.swing.Timer(500, updateLabel2());
labelTimer.start();
labelTimer.setRepeats(true);
}
private Action updateLabel2() {
return new AbstractAction("Label action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
two.setText(petStrings[index]);
index = (index + 1) % petStrings.length;
}
};
}
// Update lable one at 3 Hz
#Override
public void run() {
while (runProcess) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
one.setText(petStrings[index1]);
index1 = (index1 + 1) % petStrings.length;
}
});
try {
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Note: blocks EDT
private void printWords() {
for (int i = 0; i < petStrings.length; i++) {
String word = petStrings[i].toString();
System.out.println(word);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
three.setText(word);
}
three.setText("<html> Concurency Issues in Swing<br>"
+ " never to use Thread.sleep(int) <br>"
+ " durring EDT, simple to freeze GUI </html>");
}
public BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
}
import java.awt.*;
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 java.util.Iterator;
import javax.swing.*;
class TimeThis extends JFrame {
private static final long serialVersionUID = 1L;
private ArrayList<Word> words;
private JTextField _textField; // set by timer listener
public TimeThis() throws IOException {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
_textField.setText("loading...");
readFile(); // read file
printWords(); // print results
}
public void readFile(){
try {
BufferedReader in = new BufferedReader(new FileReader("adameve.txt"));
words = new ArrayList<Word>();
int lineNum = 1; // we read first line in start
// delimeters of line in this example only "space"
char [] parse = {' '};
String delims = new String(parse);
String line = in.readLine();
String [] lineWords = line.split(delims);
// split the words and create word object
//System.out.println(lineWords.length);
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
line = in.readLine();
in.close();
} catch (IOException e) {
}
}
private void printWords() {
final Timer timer = new Timer(100, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
class Word{
private String name;
public Word(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static void main(String[] args) throws IOException {
JFrame ani = new TimeThis();
ani.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ani.setVisible(true);
}
}
I got it working with this code... Hope it can help someone else expand on their Java knowledge. Also, if anyone has any recommendations on cleaning this up. Please do so!
You're on the right track, but you're creating the frame's inside the loop, not outside. Here's what it should be like:
private void printWords() {
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel("", SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
textLabel.setTest(w.name);
}
}

Categories