JComboBox return index value - java

I have been trying to write a game recently, and I've been coding the GUI. Since I'm a new programmer, and want to keep it simple, I want to use only a resolution selector (fullscreen maybe later). I have the CB, I have an action listener to return the value, and a button to substitute the new resolution measurements. However, every time I run the code, I try to change the resolution and nothing happens.
Anyone have any ideas?
And also, I was wondering how to make it so that there is a stock resolution on first run, but it then saves your selected resolution.
Thank you!
Jack
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Scanner;
public class GUI_Test{
private JPanel window;
private JPanel settings;
private JFrame main;
private JFrame optionsScreen;
private JLabel headerLabel;
private JLabel optionsLabel;
private JLabel resolution;
private JComboBox resolutonOption;
String[] resolutionOptions = new String[] {
"640x480", "1024x768", "1366x768", "1600x900", "1920x1080"
};
int tempResX, tempResY, res;
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int resX = gd.getDisplayMode().getWidth();
int resY = gd.getDisplayMode().getHeight();
public GUI_Test(){
prepareGUI();
}
public static void main(String[] args) {
GUI_Test GUI = new GUI_Test();
GUI.showGUIDemo();
}
private void showGUIDemo() {
JButton exit = new JButton("EXIT");
JButton options = new JButton("OPTIONS");
JButton back = new JButton("BACK");
JButton apply = new JButton("APPLY");
JComboBox <String> resolutionOption = new JComboBox<>(resolutionOptions);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
options.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsScreen.setVisible(true);
settings.setVisible(true);
window.setVisible(false);
main.setVisible(false);
}
});
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsScreen.setVisible(false);
settings.setVisible(false);
window.setVisible(true);
main.setVisible(true);
}
});
resolutionOption.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
res = resolutionOption.getSelectedIndex();
switch (res) {
case 0:
tempResX = 640;
tempResY = 480;
break;
case 1:
tempResX = 1024;
tempResY = 768;
break;
case 2:
tempResX = 1366;
tempResY = 768;
break;
case 3:
tempResX = 1600;
tempResY = 900;
break;
case 4:
tempResX = 1920;
tempResY = 1080;
break;
}
}
});
apply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resX = tempResX;
resY = tempResY;
}
});
window.add(exit);
window.add(options);
settings.add(back);
settings.add(resolutionOption);
settings.add(apply);
main.setVisible(true);
}
private void prepareGUI() {
main = new JFrame("Basic GUI");
main.setSize(resX, resY);
main.setLayout(new GridLayout(3,1));
main.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
optionsScreen = new JFrame("Options");
optionsScreen.setSize(resX, resY);
optionsScreen.setLayout(new GridLayout(4,1));
optionsScreen.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel("AGame", JLabel.CENTER);
headerLabel.setSize(100, 50);
optionsLabel = new JLabel("Settings", JLabel.CENTER);
optionsLabel.setSize(100, 50);
resolution = new JLabel("Resolution", JLabel.CENTER);
window = new JPanel();
window.setLayout(new FlowLayout());
settings = new JPanel();
settings.setLayout(new FlowLayout());
main.add(headerLabel);
main.add(window);
main.setVisible(true);
optionsScreen.add(optionsLabel);
optionsScreen.add(settings);
optionsScreen.add(resolution);
optionsScreen.setVisible(false);
settings.setVisible(false);
}
}

you should call setSize() after you change the resolution .and then call setVisible(true) for main frame. if you want to hide optionscreen window call setVisible(false) or dispose() method.
apply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resX = tempResX;
resY = tempResY;
main.setSize(resX, resY);// apply resolution
main.setVisible(true);
//optionsScreen.setVisible(false); // hide optionscreen frame
}
});

Related

JCompenents Not Moving With JFrame

I am trying to create a game about war. I am starting off with just creating a single window. I am using swing to create windows. However, when the user tries to resize the JFrame, the elements don't move with the frame. I am resizing the buttons that I use, as well as my JPanel. My code can be seen below:
Main.java:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import Numbers.Numbers;
public class Main implements ActionListener {
static JFrame frame;
static JPanel titlePane;
static JButton playButton;
static JButton explanationButton;
static JPanel explanationPane;
static JButton nextButton;
static JLabel explanationLabel;
static JButton backButton;
static int frameSize = 500;
public Main(boolean run) {
if (run) {
frame = new JFrame("War");
titlePane = new JPanel(null);
playButton = new JButton("PLAY");
explanationButton = new JButton("HOW TO PLAY");
explanationPane = new JPanel(null);
nextButton = new JButton("NEXT");
backButton = new JButton("BACK");
titlePane.setSize(frameSize, frameSize);
titlePane.add(playButton);
playButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
playButton.setBackground(Color.GRAY);
playButton.setForeground(Color.WHITE);
playButton.setVisible(true);
explanationButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/(25/11)), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
explanationButton.setBackground(Color.GRAY);
explanationButton.setForeground(Color.WHITE);
explanationButton.setVisible(true);
explanationPane.setSize(frameSize, frameSize);
explanationPane.add(nextButton);
nextButton.setBounds(225, 50, 50, 15);
nextButton.setBackground(Color.GRAY);
nextButton.setForeground(Color.WHITE);
nextButton.setVisible(true);
backButton.setBounds(225, 450, 50, 15);
backButton.setBackground(Color.GRAY);
backButton.setForeground(Color.WHITE);
backButton.setVisible(true);
frame.setSize(frameSize, frameSize);
frame.add(titlePane);
frame.add(explanationPane);
titlePane.setVisible(false);
explanationPane.setVisible(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public void switchPane(String pane) {
switch (pane) {
case "title":
titlePane.setVisible(true);
explanationPane.setVisible(false);
break;
case "explanation":
titlePane.setVisible(false);
explanationPane.setVisible(true);
break;
}
}
#Override
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
Main war = new Main(true);
war.switchPane("title");
while (true) {
if (frame.getX() != frameSize) {
frameSize = frame.getX();
}
else if (frame.getY() != frameSize) {
frameSize = frame.getY();
}
frame.setSize(frameSize, frameSize);
titlePane.setSize(frameSize, frameSize);
explanationPane.setSize(frameSize, frameSize);
playButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
explanationButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/(25/11)), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
}
}
}
Numbers.java:
package Numbers;
public class Numbers {
public static int doubleToInt(double toConvert) {
int toReturn = (int) toConvert;
return toReturn;
}
}
Any help would be appreciated! :)
Please note I am not close to finishing so please ignore the empty method.

Why Won't the Java Component JPanel won't disapear?

I was trying to set up something with the JMenu where you can switch between "pages" (JPanels) but I ran into an issue where one would not disappear after trying a few methods online. What is the error I am making?
code:
public class Window {
public static boolean NewTerrainCamPos = false;
public static String textVal;
public static String textVal2;
public static String resiveTex;
public static String resiveTex2;
public static final int Width = 1000;
public static final int Height = 720;
public static final int FPS_CAP = 120;
private static long lastFrameTime;
private static float delta;
public void createDisplay(){
ContextAttribs attribs = new ContextAttribs(3,2).withForwardCompatible(true).withProfileCore(true);
try {
Canvas openglSurface = new Canvas();
JFrame frame = new JFrame();
JPanel game = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
//..............Menu Bar...............
JMenuBar menuBar = new JMenuBar();
JMenu terrain = new JMenu("Terrain");
JMenu Home = new JMenu("Home");
menuBar.add(Home);
menuBar.add(terrain);
JMenuItem newTerrain = new JMenuItem("add Terrain");
JMenuItem editTerrain = new JMenuItem("Edit Terrain");
JMenuItem editTexture = new JMenuItem("Edit Texture");
terrain.add(newTerrain);
terrain.add(editTerrain);
terrain.add(editTexture);
frame.setJMenuBar(menuBar);
//......................................................
newTerrain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewTerrainCamPos = true;
JFrame frame2 = new JFrame();
frame2.setVisible(true);
frame2.setSize(300, 300);
//...............................
GridLayout experimentLayout = new GridLayout(3,2);
frame2.setLayout(experimentLayout);
//.....................................
JLabel xCord = new JLabel("XCoords: ");
JLabel zCord = new JLabel("ZCoords: ");
JTextField text = new JTextField();
JTextField text2 = new JTextField();
resiveTex2 = text2.getText();
text.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
resiveTex = text.getText();
}
#Override
public void removeUpdate(DocumentEvent de) {
resiveTex = text.getText();
}
#Override
public void changedUpdate(DocumentEvent de) {
//plain text components don't fire these events
}
});
text2.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
resiveTex2 = text2.getText();
}
#Override
public void removeUpdate(DocumentEvent de) {
resiveTex2 = text2.getText();
}
#Override
public void changedUpdate(DocumentEvent de) {
//plain text components don't fire these events
}
});
JButton createTerrain = new JButton("CreateTerrain");
createTerrain.addActionListener(new ActionListener(){
TIDF terrainFileID;
public void actionPerformed(ActionEvent a){
NewTerrainCamPos = false;
textVal = text.getText();
textVal2 = text2.getText();
TIDF load = new TIDF();
load.terrainIDFile();
}
});
frame2.add(xCord);
frame2.add(text);
frame2.add(zCord);
frame2.add(text2);
frame2.add(createTerrain);
}
});
editTerrain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFrame frame3 = new JFrame();
frame3.setVisible(true);
frame3.setSize(300, 300);
//......................................
GridLayout experimentLayout = new GridLayout(3,2);
frame3.setLayout(experimentLayout);
//......................................
JButton select = new JButton("Select");
String terrainLocList[] =
{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
};
JList list = new JList(terrainLocList);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setVisibleRowCount(-1);
frame3.add(list);
frame3.add(select);
}
});
editTexture.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.remove(MainPage());
frame.add(TextureEditor());
frame.revalidate();
}
});
//.........................................
frame.add(MainPage());
frame.add(game);
frame.setSize(1200, 1200);
frame.setVisible(true);
game.add(openglSurface);
game.setBounds(0, 266, 1000, 720);
openglSurface.setSize(1000, 720);
Display.setParent(openglSurface);
Display.setDisplayMode(new DisplayMode(Width, Height));
Display.create(new PixelFormat(), attribs);
frame.setTitle("Game editor 0.3");
} catch (LWJGLException e) {
e.printStackTrace();
}
GL11.glViewport(0, 0, Width, Height);
lastFrameTime = getCurrentTime();
}
public Component MainPage(){
JPanel Main = new JPanel();
Main.setBounds(400, 0, 500, 200);
Label Welcome = new Label("Welcome to: Game Editor Version 0.3");
Welcome.setFont(new Font("Monotype Corsiva",10,22));
Main.add(Welcome);
return Main;
}
public Component TextureEditor(){
JPanel TextureLayoutLook = new JPanel();
TextureLayoutLook.setBounds(60, 0, 200, 200);
Label editorVersion = new Label("Terrain Texture Editor: 0.1");
TextureLayoutLook.add(editorVersion);
return TextureLayoutLook;
}
public static boolean Returnboolean(){
return NewTerrainCamPos;
}
public static String getTex1() {
return textVal;
}
public static String getTex2(){
return textVal2;
}
public static String getTexupdate(){
return resiveTex;
}
public static String getTexupdate2(){
return resiveTex2;
}
public static void updateDisplay(){
Display.sync(FPS_CAP);
Display.update();
long currentFrameTime = getCurrentTime();
delta = (currentFrameTime - lastFrameTime)/1000f;
lastFrameTime = currentFrameTime;
}
public static float getFrameTimeSeconds(){
return delta;
}
public static void closeDisplay(){
Display.destroy();
}
private static long getCurrentTime(){
return Sys.getTime()*1000/Sys.getTimerResolution();
}
}
frame.add(MainPage());
This line builds a brand new "main page" JPanel, and adds it the the JFrame.
frame.remove(MainPage());
This line of code creates a brand new "main page" JPanel, which has never been added to the JFrame, and attempts to remove it.
This new panel can't be removed, because it was never added. You need to retain a reference to the original panel, and remove that.
JPanel main_page = MainPage();
frame.add(main_page);
//...
frame.remove(main_page);
Note: This main_page could be re-added at a future time without needing to recreate it. Just call frame.add(main_page); again. But really, you want to use the card layout manager.

Change JFrame Properties From JTabbedPane

This is the class that makes the Frame and Tabbed Panes:
package homeworkToolkitRevised;
import javax.swing.*;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.event.*;
public class MakeGUI extends JFrame
{
private static final long serialVersionUID = 1L;
JTabbedPane TabPane;
public MakeGUI()
{
this.setTitle("The Homework Toolkit!");
setSize(700, 500);
setAlwaysOnTop(false);
setNimbus();
JTabbedPane TabPane = new JTabbedPane();
add(TabPane);
TabPane.addTab("Main Menu", new MainScreen());
TabPane.addTab("Quadratic Equations", new Quadratic());
setVisible(true);
}
public void setAlwaysTop()
{
setAlwaysOnTop(true);
}
public void setNotAlwaysTop()
{
setAlwaysOnTop(false);
}
public final void setNimbus()
{
try
{
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (UnsupportedLookAndFeelException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new MakeGUI();
}
}
And this is a tab in the tabbed pane:
package homeworkToolkitRevised;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quadratic extends JPanel implements ActionListener, ItemListener
{
private static final long serialVersionUID = 1L;
JLabel lblX2 = new JLabel ("Co-Efficient Of x²:", JLabel.LEFT);
JLabel lblX = new JLabel ("Co-Efficient of x:", JLabel.LEFT);
JLabel lblNum = new JLabel ("Number:", JLabel.LEFT);
JLabel lblNature = new JLabel ("Nature Of Roots:", JLabel.LEFT);
JLabel lblVal1 = new JLabel ("Value 1:", JLabel.LEFT);
JLabel lblVal2 = new JLabel ("Value 2:", JLabel.LEFT);
JTextField tfX2 = new JTextField (20);
JTextField tfX = new JTextField (20);
JTextField tfNum = new JTextField (20);
JTextField tfNature = new JTextField (20);
JTextField tfVal1 = new JTextField (20);
JTextField tfVal2 = new JTextField (20);
JPanel[] row = new JPanel[7];
JButton btnNature = new JButton ("Nature Of Roots");
JButton btnCalc = new JButton ("Calculate");
JButton btnClear = new JButton ("Clear");
double a = 0, b = 0, c = 0;
double Val1 = 0, Val2 = 0, Discriminant = 0;
String StrVal1, StrVal2;
Quadratic()
{
setLayout(new GridLayout(8,1));
for(int i = 0; i < 7; i++)
{
row[i] = new JPanel();
add(row[i]);
row[i].setLayout(new GridLayout (1,2));
}
row[3].setLayout(new GridLayout (1,3));
row[0].add(lblX2);
row[0].add(tfX2);
row[1].add(lblX);
row[1].add(tfX);
row[2].add(lblNum);
row[2].add(tfNum);
row[3].add(btnNature);
{
btnNature.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Nature();
}
}
);
}
row[3].add(btnCalc);
{
btnCalc.setEnabled(false);
btnCalc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Calculate();
}
}
);
}
row[3].add(btnClear);
{
btnClear.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Clear();
}
}
);
}
row[4].add(lblNature);
row[4].add(tfNature);
row[5].add(lblVal1);
row[5].add(tfVal1);
row[6].add(lblVal2);
row[6].add(tfVal2);
tfNature.setEditable(false);
tfVal1.setEditable(false);
tfVal2.setEditable(false);
JCheckBox chckbxAlwaysOnTop = new JCheckBox("Always On Top");
chckbxAlwaysOnTop.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie)
{
if(ie.getStateChange() == ItemEvent.SELECTED)
{
//setAlwaysTop();
//This is method from main class to change always on top condition of jframe
}
else if (ie.getStateChange() == ItemEvent.DESELECTED)
{
//setNotAlwaysTop();
//This is method from main class to change always on top condition of jframe
}
}
});
add(chckbxAlwaysOnTop);
setVisible(true);
}
public void Calculate()
{
a = Double.parseDouble(tfX2.getText());
b = Double.parseDouble(tfX.getText());
c = Double.parseDouble(tfNum.getText());
Val1 = (-b + Math.sqrt(Discriminant)) / (2 * a);
Val2 = (-b - Math.sqrt(Discriminant)) / (2 * a);
StrVal1 = String.valueOf(Val1);
StrVal2 = String.valueOf(Val2);
tfVal1.setText(StrVal1);
tfVal2.setText(StrVal2);
tfX2.setText("");
tfX.setText("");
tfNum.setText("");
btnCalc.setEnabled(false);
}
public void Clear()
{
a = 0; b = 0; c = 0;
Val1 = 0; Val2 = 0; Discriminant = 0;
tfX2.setText("");
tfX.setText("");
tfNum.setText("");
tfVal1.setText("");
tfVal2.setText("");
tfNature.setText("");
}
public void Nature()
{
a = Double.parseDouble(tfX2.getText());
b = Double.parseDouble(tfX.getText());
c = Double.parseDouble(tfNum.getText());
Discriminant = (b*b) - (4*(a*c));
if (Discriminant == 0)
{
tfNature.setText("Equal");
btnCalc.setEnabled(true);
}
else if (Discriminant < 0)
{
tfNature.setText("Imaginary");
}
else
{
tfNature.setText("Real, Distinct");
btnCalc.setEnabled(true);
}
}
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
}
public void itemStateChanged(ItemEvent arg0)
{
// TODO Auto-generated method stub
}
}
So what I want to do is to add a checkbox to the tab that allows me to set the property of the JFrame made in the main class to be always on top.
First of all I don't understand how to call the method properly so that it alters the always on top property. I tried making an object for it and also tried making the methods static but it just doesn't work.
What I would like to know is what modifier to use for the methods and how to alter properties of parent JFrame from inside a JTabbedPane.
Thanks.
EDIT: It would also work if I could add this checkbox to the JFrame itself like below the JTabbed Pane or something which would make it easier to manage with multiple tabs.

JComboBox ActionEvent performs with multiple comboboxes?

I am performing actions for 2 combo boxes which involves in changing the background color of JLabel. Here is my code,
public class JavaApplication8 {
private JFrame mainFrame;
private JLabel signal1;
private JLabel signal2;
private JPanel s1Panel;
private JPanel s2Panel;
public JavaApplication8()
{
try {
prepareGUI();
} catch (ClassNotFoundException ex) {
Logger.getLogger(JavaApplication8.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) throws
ClassNotFoundException
{
JavaApplication8 swingControl = new JavaApplication8();
swingControl.showCombobox1();
}
public void prepareGUI() throws ClassNotFoundException
{
mainFrame = new JFrame("Signal");
mainFrame.setSize(300,200);
mainFrame.setLayout(new GridLayout(3, 0));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
signal1 = new JLabel("Signal 1",JLabel.LEFT);
signal1.setSize(100,100);
signal1.setOpaque(true);
signal2 = new JLabel("Signal 2",JLabel.LEFT);
signal2.setSize(100,100);
signal2.setOpaque(true);
final DefaultComboBoxModel light = new DefaultComboBoxModel();
light.addElement("Red");
light.addElement("Green");
final JComboBox s1Combo = new JComboBox(light);
s1Combo.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s1Combo.getSelectedIndex() == 0)
{
signal1.setBackground(Color.RED);
}
else
{
signal1.setBackground(Color.GREEN);
}
}
});
final JComboBox s2Combo1 = new JComboBox(light);
s2Combo1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s2Combo1.getSelectedIndex() == 0)
{
signal2.setBackground(Color.RED);
}
else
{
signal2.setBackground(Color.GREEN);
}
}
});
s1Panel = new JPanel();
s1Panel.setLayout(new FlowLayout());
JScrollPane ListScrollPane = new JScrollPane(s1Combo);
s1Panel.add(signal1);
s1Panel.add(ListScrollPane);
s2Panel = new JPanel();
s2Panel.setLayout(new FlowLayout());
JScrollPane List1ScrollPane = new JScrollPane(s2Combo1);
s2Panel.add(signal2);
s2Panel.add(List1ScrollPane);
mainFrame.add(s1Panel);
mainFrame.add(s2Panel);
String[] columnNames = {"Signal 1","Signal 2"};
Object[][] data = {{"1","1"}};
final JTable table = new JTable(data,columnNames);
JScrollPane tablepane = new JScrollPane(table);
table.setFillsViewportHeight(true);
mainFrame.add(tablepane);
mainFrame.setVisible(true);
}
}
When Executed, If I change the item from combo box 1, the 2nd combo box also performs the change. Where did I go wrong?
Yours is a simple solution: don't have the JComboBoxes share the same model. If they share the same model, then changes to the selected item of one JComboBox causes a change in the shared model which changes the view of both JComboBoxes.
I wold use a method to create your combo-jlabel duo so as not to duplicate code. For instance:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class App8 extends JPanel {
private static final int COMBO_COUNT = 2;
private static final String SIGNAL = "Signal";
private List<JComboBox<ComboColor>> comboList = new ArrayList<>();
public App8() {
setLayout(new GridLayout(0, 1));
for (int i = 0; i < COMBO_COUNT; i++) {
DefaultComboBoxModel<ComboColor> cModel = new DefaultComboBoxModel<>(ComboColor.values());
JComboBox<ComboColor> combo = new JComboBox<>(cModel);
add(createComboLabelPanel((i + 1), combo));
comboList.add(combo);
}
}
private JPanel createComboLabelPanel(int index, final JComboBox<ComboColor> combo) {
JPanel panel = new JPanel();
final JLabel label = new JLabel(SIGNAL + " " + index);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
label.setOpaque(true);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ComboColor cColor = (ComboColor) combo.getSelectedItem();
label.setBackground(cColor.getColor());
}
});
panel.add(label);
panel.add(combo);
return panel;
}
private static void createAndShowGui() {
App8 mainPanel = new App8();
JFrame frame = new JFrame("App8");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
enum ComboColor {
RED("Red", Color.RED),
GREEN("Green", Color.GREEN);
private String text;
private Color color;
public String getText() {
return text;
}
public Color getColor() {
return color;
}
private ComboColor(String text, Color color) {
this.text = text;
this.color = color;
}
#Override
public String toString() {
return text;
}
}

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