from my MainFrame I create a internal Frame and add that to my desktop pane, but the internal Frame just won't show up. I tried to figure it out for 3 hours now and I kinda need some help with it. Before I implemented the observer pattern it just worked fine. So I thought it got something to do with that and changed some stuff and double checked the crucial code. No solution so far. I just realized how crappy my english is sometimes. Sorry for that!
The 2 code blocks are already shortened. Sorry that they are still pretty long. But I am just not sure where I made the mistake. If you need more code or anything else, just tell me. Thank you very much in advance.
This is the code of my main frame:
public class LangtonsAmeise extends JFrame implements ActionListener {
private JDesktopPane desk;
private JPanel panelButtons;
JMenuBar jmb;
JMenu file,modus;
JMenuItem load,save, exit, mSetzen,mMalen,mLaufen;
JSlider slider;
static int xInt, yInt,xFrame=450,yFrame=450;
static boolean bSetzen = false, bMalen = false, running = false;
Random randomGenerator = new Random();
JLabel xLabel, yLabel, speed, statusText,status;
JButton start, stop, addAnt;
JTextField xField, yField;
public LangtonsAmeise() {
// Desktop
desk = new JDesktopPane();
getContentPane().add(desk, BorderLayout.CENTER);
/* Those 4 lines work just fine. Internal Frame gets displayed.
JInternalFrame j = new JInternalFrame();
desk.add(j);
j.setSize(new Dimension(300,300));
j.setVisible(true);
*/
speed = new JLabel("Geschwindigkeit");
xLabel = new JLabel("x:");
yLabel = new JLabel("y:");
xLabel.setHorizontalAlignment(JLabel.RIGHT);
yLabel.setHorizontalAlignment(JLabel.RIGHT);
xLabel.setOpaque(true);
yLabel.setOpaque(true);
xField = new JTextField();
yField = new JTextField();
xField.setDocument(new IntegerDocument(2));
yField.setDocument(new IntegerDocument(2));
start = new JButton("Fenster erstellen");
stop = new JButton("Stopp");
start.setMargin(new Insets(0, 0, 0, 0));
stop.setMargin(new Insets(0, 0, 0, 0));
// Buttons
panelButtons = new JPanel();
panelButtons.setLayout(new GridLayout());
panelButtons.add(start);
panelButtons.add(xLabel);
panelButtons.add(xField);
panelButtons.add(yLabel);
panelButtons.add(yField);
panelButtons.add(speed);
panelButtons.add(slider);
panelButtons.add(new Panel());
panelButtons.add(stop);
start.addActionListener(this);
stop.addActionListener(this);
add(panelButtons, BorderLayout.NORTH);
statusText = new JLabel("Aktueller Modus:");
status = new JLabel("Stopp");
// JMenuBar
jmb = new JMenuBar();
setJMenuBar(jmb);
file = new JMenu("Datei");
modus = new JMenu("Modus");
mLaufen = new JMenuItem("Laufen");
mMalen = new JMenuItem("Malen");
mSetzen = new JMenuItem("Setzen");
load = new JMenuItem("Simulation laden");
save = new JMenuItem("Simulation speichern");
mSetzen.addActionListener(this);
mMalen.addActionListener(this);
mLaufen.addActionListener(this);
exit = new JMenuItem("Exit");
file.add(save);
file.add(load);
file.addSeparator();
file.add(exit);
save.addActionListener(this);
load.addActionListener(this);
modus.add(mLaufen);
modus.add(mSetzen);
modus.add(mMalen);
jmb.add(file);
jmb.add(modus);
for (int i = 0; i < 20; i++) {
jmb.add(new JLabel(" "));
}
jmb.add(statusText);
jmb.add(status);
setSize(new Dimension(1000, 900));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height
/ 2 - this.getSize().height / 2);
xField.setText("5");
yField.setText("5");
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Fenster erstellen")) {
if (xField.getText().equals("") || yField.getText().equals("")) {
new popUpWindow(
"Sie müssen eine Zahl zwischen 2 und 99 angeben!!");
} else {
xInt = Integer.parseInt(xField.getText());
yInt = Integer.parseInt(yField.getText());
state s = new state();
kindFenster k = new kindFenster(s, xInt, yInt);
s.addObserver(k);
addChild(k, this.getSize().width, this.getSize().height);
}
}
if (e.getActionCommand().equals("Stopp")) {
running=!running;
status.setText("Stopp");
}
}
public void addChild(JInternalFrame kind, int xPixel, int yPixel) {
// kind.setSize(370, 370);
kind.setLocation(randomGenerator.nextInt(xPixel - kind.getSize().height),
randomGenerator.nextInt(yPixel - kind.getSize().height - 100));
kind.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
desk.add(kind);
kind.setVisible(true);
kind.repaint();
kind.validate();
}
public static void main(String[] args) {
LangtonsAmeise hauptFenster = new LangtonsAmeise();
}
}
And this is my Internal Frame:
public class kindFenster extends JInternalFrame implements ActionListener,
Serializable,Observer {
/**
*
*/
private static final long serialVersionUID = 8939449766068226519L;
static int nr = 0;
static int x,y,xScale,yScale,xFrame,yFrame;
static int sleeptime;
state s;
ArrayList<JButton> jbArray = new ArrayList<>();
ArrayList<ImageIcon> ameisen = new ArrayList<ImageIcon>();
public static ArrayList<AmeiseThread> threadList = new ArrayList<>();
Color alteFarbe, neueFarbe;
JButton save, addAnt;
JPanel panelButtonsKind;
JSlider sliderKind;
public JPanel panelSpielfeld;
static SetzenActionListener sal = new SetzenActionListener();
static MouseMotionActionListener mmal = new MouseMotionActionListener();
public kindFenster(state s,int x, int y) {
super("Kind " + (++nr), true, true, true, true);
setLayout(new BorderLayout());
this.s=s;
setSize(new Dimension(xFrame, yFrame));
panelSpielfeld = new JPanel();
panelSpielfeld.setLayout(new GridLayout(y, x));
panelButtonsKind = new JPanel();
panelButtonsKind.setLayout(new GridLayout(1, 3));
save = new JButton("Simulation speichern");
addAnt = new JButton("Ameise hinzufügen");
save.setMargin(new Insets(0, 0, 0, 0));
addAnt.setMargin(new Insets(0, 0, 0, 0));
addAnt.addActionListener(this);
save.addActionListener(this);
sliderKind = new JSlider(JSlider.HORIZONTAL, 1, 10, 5);
sliderKind.setSnapToTicks(true);
sliderKind.setPaintTicks(true);
sliderKind.setPaintTrack(true);
sliderKind.setMajorTickSpacing(1);
sliderKind.setPaintLabels(true);
sliderKind.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (threadList.size() >= 0) {
for (AmeiseThread t : threadList) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
int speed = source.getValue();
sleeptime = 1000 / speed;
}
}
}
}
});
panelButtonsKind.add(save);
panelButtonsKind.add(sliderKind);
panelButtonsKind.add(addAnt);
add(panelButtonsKind, BorderLayout.NORTH);
add(panelSpielfeld, BorderLayout.CENTER);
this.addComponentListener(new MyComponentAdapter());
setVisible(true);
repaint();
validate();
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Ameise hinzufügen")) {
threadList.add(new AmeiseThread(this));
threadList.get(threadList.size() - 1).start();
}
if (e.getActionCommand().equals("Simulation speichern")) {
OutputStream fos = null;
try {
fos = new FileOutputStream("test");
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(this );
} catch (IOException e1) {
System.err.println(e1);
} finally {
try {
fos.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
I think it is because you didn't set size for your JInternalFrame. In your code it is as a comment:
//kind.setSize(370, 370);
when I remove "//" it works for me.
Related
ive searched online for the answer for a few hours now, so far i havent found anything helpful, i have a JDialog that is supposed to send an object back to the JPanel that called it, after running the code several times i noticed that the JPanel Constructor Finishes before i can press the Save button inside the JDialog,
my problem is this,
how do i pass the object from the JDialog to the JPanel and in which part of the Jpanel Code do i write it?
Here is the JPanel Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class AquaPanel extends JPanel implements ActionListener
{
private JFrame AQF;
private BufferedImage img;
private HashSet<Swimmable> FishSet;
private int FishCount;
private AddAnimalDialog JDA;
public AquaPanel(AquaFrame AQ)
{
super();
FishCount=0;
this.setSize(800, 600);
this.AQF = AQ;
gui();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
// if(!FishSet.isEmpty())
// {
// Iterator ITR = FishSet.iterator();
//
// while(ITR.hasNext())
// {
// ((Swimmable) ITR.next()).drawAnimal(g);
// }
// }
}
private void AddAnim()
{
Swimmable test = null;
JDA = new AddAnimalDialog(test);
JDA.setVisible(true);//shows jdialog box needs to set to false on new animal
}
private void Sleep()
{
}
private void Wake()
{
}
private void Res()
{
}
private void Food()
{
}
private void Info()
{
}
private void gui()
{
JPanel ButtonPanel = new JPanel();
Makebuttons(ButtonPanel);
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
ButtonPanel.setLayout(new GridLayout(1,0));
this.add(ButtonPanel,BorderLayout.SOUTH);
}
private void Makebuttons(JPanel ButtonPanel)
{
JButton Addanim = new JButton("Add Animal");
Addanim.setBackground(Color.LIGHT_GRAY);
Addanim.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AddAnim();
}
});
JButton Sleep = new JButton("Sleep");
Sleep.setBackground(Color.LIGHT_GRAY);
Sleep.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Sleep();
}
});
JButton Wake = new JButton("Wake Up");
Wake.setBackground(Color.LIGHT_GRAY);
Wake.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Wake();
}
});
JButton Res = new JButton("Reset");
Res.setBackground(Color.LIGHT_GRAY);
Res.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Res();
}
});
JButton Food = new JButton("Food");
Food.setBackground(Color.LIGHT_GRAY);
Food.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Food();
}
});
JButton Info = new JButton("Info");
Info.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Info();
}
});
Info.setBackground(Color.LIGHT_GRAY);
JButton ExitAQP = new JButton("Exit");
ExitAQP.setBackground(Color.LIGHT_GRAY);
ExitAQP.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
ButtonPanel.add(Addanim);
ButtonPanel.add(Sleep);
ButtonPanel.add(Wake);
ButtonPanel.add(Res);
ButtonPanel.add(Food);
ButtonPanel.add(Info);
ButtonPanel.add(ExitAQP);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()=="Confirm Add")
{
if(JDA.GetDone())
{
FishSet.add(JDA.GetAnim()) ;
JOptionPane.showMessageDialog(this, JDA.GetAnim().getAnimalName());
}
}
}
public void setBackgr(int sel)
{
switch (sel)
{
case 0:
img=null;
this.setBackground(Color.WHITE);
break;
case 1:
img=null;
this.setBackground(Color.BLUE);
break;
case 2:
try {
img = ImageIO.read(new File("src/aquarium_background.jpg"));
} catch (IOException e) {
System.out.println("incorrect input image file path!!!!");
e.printStackTrace();
}
}
}
private void ConfirmAnimal()
{
if(JDA.GetAnim()!=null)
{
JOptionPane.showMessageDialog(this, "fish exists");
}
else
{
JOptionPane.showMessageDialog(this, "fish doesn't exists");
}
}
}
and the JDialog Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddAnimalDialog extends JDialog
{
private JTextField SizeField;
private JTextField HSpeedField;
private JTextField VSpeedField;
private int SelectedAnimal;
private int SelectedColor;
private Boolean IsDone;
private JButton SaveBTN;
Swimmable Animal;
public AddAnimalDialog(Swimmable Anim)
{
super();
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
IsDone = false;
gui();
Anim = Animal;
}
private void gui()
{
this.setSize(new Dimension(400, 300));
JPanel panel = new JPanel();
this.getContentPane().add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{151, 62, 63, 0};
gbl_panel.rowHeights = new int[]{20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel AnimName = new JLabel("Animal Type:");
GridBagConstraints gbc_AnimName = new GridBagConstraints();
gbc_AnimName.insets = new Insets(0, 0, 5, 5);
gbc_AnimName.gridx = 0;
gbc_AnimName.gridy = 1;
panel.add(AnimName, gbc_AnimName);
JComboBox AnimTypecomboBox = new JComboBox();
AnimTypecomboBox.addItem("Fish");
AnimTypecomboBox.addItem("Jellyfish");
GridBagConstraints gbc_AnimTypecomboBox = new GridBagConstraints();
gbc_AnimTypecomboBox.insets = new Insets(0, 0, 5, 5);
gbc_AnimTypecomboBox.anchor = GridBagConstraints.NORTH;
gbc_AnimTypecomboBox.gridx = 1;
gbc_AnimTypecomboBox.gridy = 1;
panel.add(AnimTypecomboBox, gbc_AnimTypecomboBox);
JLabel AnimSize = new JLabel("Size(between 20 to 320):");
GridBagConstraints gbc_AnimSize = new GridBagConstraints();
gbc_AnimSize.insets = new Insets(0, 0, 5, 5);
gbc_AnimSize.gridx = 0;
gbc_AnimSize.gridy = 2;
panel.add(AnimSize, gbc_AnimSize);
SizeField = new JTextField();
GridBagConstraints gbc_SizeField = new GridBagConstraints();
gbc_SizeField.insets = new Insets(0, 0, 5, 5);
gbc_SizeField.fill = GridBagConstraints.HORIZONTAL;
gbc_SizeField.gridx = 1;
gbc_SizeField.gridy = 2;
panel.add(SizeField, gbc_SizeField);
SizeField.setColumns(10);
JLabel HSpeed = new JLabel("Horizontal Speed(between 1 to 10):");
GridBagConstraints gbc_HSpeed = new GridBagConstraints();
gbc_HSpeed.insets = new Insets(0, 0, 5, 5);
gbc_HSpeed.gridx = 0;
gbc_HSpeed.gridy = 3;
panel.add(HSpeed, gbc_HSpeed);
HSpeedField = new JTextField();
GridBagConstraints gbc_HSpeedField = new GridBagConstraints();
gbc_HSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_HSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_HSpeedField.gridx = 1;
gbc_HSpeedField.gridy = 3;
panel.add(HSpeedField, gbc_HSpeedField);
HSpeedField.setColumns(10);
JLabel VSpeed = new JLabel("Vertical Speed(between 1 to 10):");
GridBagConstraints gbc_VSpeed = new GridBagConstraints();
gbc_VSpeed.insets = new Insets(0, 0, 5, 5);
gbc_VSpeed.gridx = 0;
gbc_VSpeed.gridy = 4;
panel.add(VSpeed, gbc_VSpeed);
VSpeedField = new JTextField();
GridBagConstraints gbc_VSpeedField = new GridBagConstraints();
gbc_VSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_VSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_VSpeedField.gridx = 1;
gbc_VSpeedField.gridy = 4;
panel.add(VSpeedField, gbc_VSpeedField);
VSpeedField.setColumns(10);
JLabel lblAnimalColor = new JLabel("Animal Color:");
GridBagConstraints gbc_lblAnimalColor = new GridBagConstraints();
gbc_lblAnimalColor.insets = new Insets(0, 0, 5, 5);
gbc_lblAnimalColor.gridx = 0;
gbc_lblAnimalColor.gridy = 5;
panel.add(lblAnimalColor, gbc_lblAnimalColor);
JComboBox ColorComboBox = new JComboBox();
ColorComboBox.setModel(new DefaultComboBoxModel(new String[] {"Red", "Magenta", "Cyan", "Blue", "Green"}));
GridBagConstraints gbc_ColorComboBox = new GridBagConstraints();
gbc_ColorComboBox.insets = new Insets(0, 0, 5, 5);
gbc_ColorComboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_ColorComboBox.gridx = 1;
gbc_ColorComboBox.gridy = 5;
panel.add(ColorComboBox, gbc_ColorComboBox);
JButton btnAddAnimal = new JButton("Confirm Add");
GetInput(btnAddAnimal,AnimTypecomboBox,ColorComboBox);
GridBagConstraints gbc_btnAddAnimal = new GridBagConstraints();
gbc_btnAddAnimal.insets = new Insets(0, 0, 0, 5);
gbc_btnAddAnimal.gridx = 0;
gbc_btnAddAnimal.gridy = 9;
panel.add(btnAddAnimal, gbc_btnAddAnimal);
JButton btnClear = new JButton("Clear");
GridBagConstraints gbc_btnClear = new GridBagConstraints();
gbc_btnClear.gridx = 2;
gbc_btnClear.gridy = 9;
panel.add(btnClear, gbc_btnClear);
}
private Color Getcolor(Object obj)
{
Color clr=Color.RED;
if(obj instanceof String)
{
switch((String)obj)
{
case "Red":
clr = Color.RED;
break;
case "Magenta":
clr = Color.MAGENTA;
break;
case "Cyan":
clr = Color.CYAN;
break;
case "Blue":
clr = Color.BLUE;
break;
case "Green":
clr = Color.GREEN;
break;
}
}
return clr;
}
private Fish MakeFish(int size,Color col,int horSpeed,int verSpeed)
{
return new Fish(size,col,horSpeed,verSpeed);
}
private Jellyfish MakeJellyfish(int size,Color col,int horSpeed,int verSpeed)
{
return new Jellyfish(size,col,horSpeed,verSpeed);
}
public Swimmable GetAnim()
{
return Animal;
}
public Boolean GetDone()
{
return IsDone;
}
private void GetInput(JButton Jbtn,JComboBox type,JComboBox col)
{
Jbtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Fish"))
{
Color clr=Color.RED;
Object tmp = col.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeFish(size,clr,Hspeed,VSpeed);
}
else if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Jellyfish"))
{
Color clr=Color.RED;
Object tmp = type.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeJellyfish(size,clr,Hspeed,VSpeed);
}
IsDone=true;
Hide();
SaveBTN = Jbtn;
}
});
}
private void Hide()
{
this.setVisible(false);
}
public JButton GetBTN()
{
return SaveBTN;
}
}
So in short in the JDialog i need to get information from comboboxes and texfields and send that data to an object constructor, and on the "Save" button click i need to transfer the Object from the JDialog that i created with the constructor to the JPanel, how do i do it?
i realized i can send the JPanel to the JDialog and in the JDialog's code where i create the object, i modify the Jpanel's Hashset accordingly
So I'm creating a game in Java and I ran into a little problem. Whenever I run the application the GUI does not show on the screen and the only way to close the application is to use the Windows Task Manager. In the application, you choose a username and click an enter button which creates a new window in which the game is played. But after you click the button, none of the GUI loads and you can't close the application.
Basically, when you click the button, a method is called that disposes the current window and starts the game window. The code for that method is below:
public void login(String name) {
String[] args={};
dispose();
SingleplayerGUI.main(args);
}
And here is the code of the SingleplayerGUI class:
public SingleplayerGUI(String userName, Singleplayer sp) {
this.userName = userName;
setResizable(false);
setTitle("Console Clash Singleplayer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(880, 550);
setLocationRelativeTo(null);
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
} catch (IOException e1) {
e1.printStackTrace();
}
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 28, 815, 30, 7 }; // SUM = 880
gbl_contentPane.rowHeights = new int[] { 25, 485, 40 }; // SUM = 550
contentPane.setLayout(gbl_contentPane);
history = new JTextPane();
history.setEditable(false);
JScrollPane scroll = new JScrollPane(history);
caret = (DefaultCaret) history.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints scrollConstraints = new GridBagConstraints();
scrollConstraints.insets = new Insets(0, 0, 5, 5);
scrollConstraints.fill = GridBagConstraints.BOTH;
scrollConstraints.gridx = 0;
scrollConstraints.gridy = 0;
scrollConstraints.gridwidth = 2;
scrollConstraints.gridheight = 2;
scrollConstraints.weightx = 1;
scrollConstraints.weighty = 1;
scrollConstraints.insets = new Insets(0, 0, 5, -64);
contentPane.add(scroll, scrollConstraints);
txtMessage = new JTextField();
txtMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
}
});
GridBagConstraints gbc_txtMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(0, 0, 0, 25);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(txtMessage, gbc_txtMessage);
chat = new JTextPane();
chat.setEditable(false);
JScrollPane chatscroll = new JScrollPane(chat);
caret = (DefaultCaret) chat.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints chatscrollConstraints = new GridBagConstraints();
chatscrollConstraints.insets = new Insets(0, 0, 5, 5);
chatscrollConstraints.fill = GridBagConstraints.BOTH;
chatscrollConstraints.gridx = 0;
chatscrollConstraints.gridy = 0;
chatscrollConstraints.gridwidth = 2;
chatscrollConstraints.gridheight = 2;
chatscrollConstraints.weightx = 1;
chatscrollConstraints.weighty = 1;
chatscrollConstraints.insets = new Insets(150, 600, 5, -330);
contentPane.add(chatscroll, chatscrollConstraints);
chatMessage = new JTextField();
final String name = this.userName;
chatMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
chatconsole(name + ": " + chatMessage.getText());
}
}
});
GridBagConstraints gbc_chatMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(000, 600, 000, -330);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(chatMessage, gbc_txtMessage);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
});
GridBagConstraints gbc_btnSend = new GridBagConstraints();
gbc_btnSend.insets = new Insets(0, 0, 0, 275);
gbc_btnSend.gridx = 2;
gbc_btnSend.gridy = 2;
gbc_btnSend.weightx = 0;
gbc_btnSend.weighty = 0;
contentPane.add(btnSend, gbc_btnSend);
list = new JList();
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 600, 330, -330);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
gbc_list.gridwidth = 2;
gbc_list.gridheight = 2;
JScrollPane p = new JScrollPane();
p.setViewportView(list);
contentPane.add(p, gbc_list);
list.setFont(new Font("Verdana", 0, 24));
System.out.println("HEY");
setVisible(true);
new SwingWorker<Void, String>() {
protected Void doInBackground() throws Exception {
Scanner s = new Scanner(outPipe);
while (s.hasNextLine()) {
String line = s.nextLine();
publish(line);
}
return null;
}
#Override protected void process(java.util.List<String> chunks) {
for (String line : chunks) {
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), line + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
}
}.execute();
Singleplayer spp = new Singleplayer();
Singleplayer.startOfGame();
setVisible(true);
}
public static void console(String message, Color color) {
txtMessage.setText("");
try {
StyledDocument doc = history.getStyledDocument();
Style style = history.addStyle("", null);
StyleConstants.setForeground(style, color);
doc.insertString(doc.getLength(), message + "\r\n", style);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void console(String message) {
txtMessage.setText("");
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public void chatconsole(String message) {
chatMessage.setText("");
try {
Document doc = chat.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void single() {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
public static void main(String[] args) {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
And the singleplayer class:
public static void startOfGame(){
System.out.println("HEY");
SingleplayerGUI.console("Welcome to Console Clash Pre Alpha Version 1!");
SingleplayerGUI.console("Created by Drift");
SingleplayerGUI.console("Published by Boring Games");
SingleplayerGUI.console("");
SingleplayerGUI.console("");
menuScreen();
}
static void menuScreen() {
Scanner scan = new Scanner(System.in);
System.out.println("To play the game, type 'start'. To quit, type 'quit'.");
String menu = scan.nextLine();
if (menu.equals("start")) {
start();
} else if (menu.equals("quit")) {
quit();
} else {
menuScreen();
}
}
private static void quit() {
SingleplayerGUI.console("You quit the game.");
}
private static void start() {
SingleplayerGUI.console("You started the game.");
}
So far I've figured out that the problem most likey occurs when adding the outPipe to the console. Would I be able to fix this or am I just not able to use outPipes with this application?
Thanks in advance for your help.
The setVisible() method is invoked twice.. Remove the second setVisible() call after the Singleplayer.startOfGame(); line in SingleplayerGUI constructor.
I have a program here that changes an avatars hat and earrings
the problem is that it only restarts once (the load button only works once)
This is what I have:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.JTextArea;
public class Lab14_Navarro extends JFrame {
private int x,y,z;
private Container game;
private JComboBox Head;
private JComboBox Ear;
private JLabel Avatar;
private JTextArea details;
private String []Hat = {"No Hat", "Captain Hat", "Black Leather Hat"};
private JButton load;
private String []Earrings = {"No Earrings", "Silver Dangling Earrings", "Gold Dangling Earrings"};
private ImageIcon [] Accessories =
{ new ImageIcon("blackleather.PNG"),//0
new ImageIcon("blackleather_goldear.PNG"),//1
new ImageIcon("blackleather_silverear.PNG"),//2
new ImageIcon("captainhat.PNG"),//3
new ImageIcon("captainhat_goldear.PNG"),//4
new ImageIcon("captainhat_silverear.PNG"),//5
new ImageIcon("goldear.PNG"),//6
new ImageIcon("noaccessories.PNG"),//7
new ImageIcon("silverear.PNG")};//8
/**
* Creates a new instance of <code>Lab14_Navarro</code>.
*/
public Lab14_Navarro() {
getContentPane().removeAll();
setTitle("Avatar!");
setSize(250,450);
setLocationRelativeTo(null);
game = getContentPane();
game.setLayout(new FlowLayout());
Head = new JComboBox(Hat);
Ear = new JComboBox(Earrings);
Avatar = new JLabel(Accessories[7]);
load = new JButton("Load Image");
details = new JTextArea("AVATAR DETAILS: "+"\n"+" Hat: "+Hat[Head.getSelectedIndex()]+"\n"+" Earrings: "+Earrings[Ear.getSelectedIndex()]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);
Head.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox temphead = (JComboBox) e.getSource();
int temphat = (int) temphead.getSelectedIndex();
x = temphat;
}
});
Ear.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox tempear = (JComboBox) e.getSource();
int tempearrings = (int) tempear.getSelectedIndex();
y = tempearrings;
}
});
load.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
getContentPane().removeAll();
if(x==0&&y==0){
z = 7;
}
if(x==0&&y==1){
z = 8;
}
if(x==0&&y==2){
z = 6;
}
if(x==1&&y==0){
z = 3;
}
if(x==1&&y==1){
z = 5;
}
if(x==1&&y==2){
z = 4;
}
if(x==2&&y==0){
z = 0;
}
if(x==2&&y==1){
z = 2;
}
if(x==2&&y==2){
z = 1;
}
setTitle("Avatar");
setSize(250,450);
setLocationRelativeTo(null);
game = getContentPane();
game.setLayout(new FlowLayout());
Head = new JComboBox(Hat);
Ear = new JComboBox(Earrings);
Avatar = new JLabel(Accessories[z]);
load = new JButton("Load Image");
details = new JTextArea("AVATAR DETAILS: "+"\n"+" Hat: "+Hat[x]+"\n"+" Earrings: "+Earrings[y]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);
}
});
}
public static void main(String[] args) {
Lab14_Navarro fs = new Lab14_Navarro();
fs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Any help is accepted thanks
I just started Java so I'm not that good... yet
When you write, for the second time:
load = new JButton("Load Image");
you're creating a new button, however, you are not giving it a new ActionListener
On another note, you don't need to create a new Button, your original load button is still there, you need only to add it to the contentPane again.
I am making a GUI app in which on click of button we read a binary file and display the data in a TextArea (Data is 327680 bytes).
Now if I use textArea.setLine(true) then it slows down the execution and it takes about 1 minute to execute and dislpays value.
But if I dont use textArea.setLine(true) then code executes in less than 1 sec.
UPDATED CODE.
public class App{
private static final String INPUT_FILE = "E:\\arun\\files\\Capture_Mod1.BIN";
private static final String OUTPUT_FILE = "E:\\arun\\files\\ISO_Write.BIN";
private static final String IMAGE_FILE = "E:\\arun\\files\\Image.jpg";
private JFrame frame;
private JTextArea textArea;
private JButton btnNewButton;
private ISOImageDataWorker worker;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App window = new App();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public App() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
textArea = new JTextArea(5, 20); // **HERE IS THE PROBLEM**
textArea.setLineWrap(true);
textArea.setWrapStyleWord( true );
JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
GridBagConstraints gbc_textArea = new GridBagConstraints();
gbc_textArea.insets = new Insets(0, 0, 5, 0);
gbc_textArea.gridx = 0;
gbc_textArea.gridy = 1;
frame.getContentPane().add(scrollPane, gbc_textArea);
btnNewButton = new JButton("ISO 19794 Data");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 2;
frame.getContentPane().add(btnNewButton, gbc_btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
worker = new ISOImageDataWorker();
worker.execute();
}
});
}
private class ISOImageDataWorker extends SwingWorker<String , Object>{
#Override
protected String doInBackground() throws Exception {
String str = processData();
return str;
}
#Override
protected void done(){
try {
System.out.println("cm1");
textArea.setText(get());
System.out.println("cm2");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String processData(){
DataReadWrite data = new DataReadWrite();
//Read data
byte[] imageData = data.readData(INPUT_FILE);
System.out.println("Image data length is : "+ imageData.length);
// Generate Finger Image Data General Header
FingerImageDataGeneralHeader generateHeader = new FingerImageDataGeneralHeader();
byte[] resultData = generateHeader.createGeneralHeader(imageData);
// Write data to binary file
data.writeData(resultData, OUTPUT_FILE);
// Create Image from binary data
CreateTiff createTiff = new CreateTiff();
createTiff.create(resultData, IMAGE_FILE);
String str = bytesToHex(resultData);
return str;
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
return sb.toString();
}
}
I don't know what I am doin wrong. Please Help.
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
>> processData(); <<
textArea.setText(str);
}
});
Don't execute time-consuming code on the GUI-thread (EDT). Use SwingWorker.
See How SwingWorker works.
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);
}
}