Change JFrame Properties From JTabbedPane - java

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.

Related

How can I enable/disable a JTextField with a JCheckBox? or what's wrong with my code?

I'm newbie in programming java, I have an array of JCheckBox next to an array of JTextfield.
I need to make a CheckBox Deactivate a JTextField when it's checked, but I don't have success in this
How can I make it works with actionlisteners?
This is my code:
public class Checklist_Complete extends JFrame {
private JLabel description;
private JButton send;
private JTextField text[]=new JTextField[10];
private JCheckBox cb[]=new JCheckBox[10];
public Checklist_Complete() {
setTitle("Activities");
setSize(500,300);
setupWidgets();
setVisible(true);
}
private void setupWidgets() {
JPanel pn_center = new JPanel(new GridLayout(10,1));
JPanel pn_west = new JPanel(new GridLayout(10,1));
description = new JLabel("List your activities and uncheck the irrelevant ones");
send = new JButton("Send Checklist");
for (int i=0; i<10; i++) {
text[i] = new JTextField();
cb[i] = new JCheckBox("", true);
}
add(description, BorderLayout.NORTH);
add(pn_center, BorderLayout.CENTER);
add(pn_west, BorderLayout.WEST);
add(send, BorderLayout.SOUTH);
for (int i=0; i<10; i++){
pn_center.add(text[i]);
pn_west.add(cb[i]);
}
}
private void setupEvents() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int i=0; i<10; i++) {
cb[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if(cb[i].isSelected()){
text[i].setEnabled(false);
} else{
text[i].setEnabled(true);
}
}
});
}
}
public static void main(String[] args) {
new Checklist_Complete();
}
}
Here is a quick solution with an ItemListener.
private void setupEvents() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int i=0; i<10; i++) {
final int finalI = i;
cb[i].addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
text[finalI].setEnabled(e.getStateChange() == ItemEvent.SELECTED);
}
});
}
}
You can also do it with an ActionListener but the solution is a bit of a hack, and it is not as elegant. I am posting this because you can solve your issue like this also:
private void setupEvents() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int i=0; i<10; i++) {
final int finalI = i;
cb[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
text[finalI].setEnabled(!text[finalI].isEnabled() && e.getID() == ActionEvent.ACTION_PERFORMED);
}
});
}
}
Problems:
You never call setupEvents() and so the code in this method is never called
You will need to make local fields final if you want to use them within an inner anonymous class.
So:
private void setupEvents() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int i=0; i<10; i++) {
final int finalIndex = i;
cb[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if(cb[finalIndex].isSelected()){
text[finalIndex].setEnabled(false);
} else{
text[finalIndex].setEnabled(true);
}
}
});
}
}
I would do things a little differently, and to my eye cleaner. e.g.,
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class CheckList2 extends JPanel {
public static final int TEXT_FIELD_COUNT = 10;
private List<JTextField> fields = new ArrayList<>();
private JButton sendBtn = new JButton(new SendAction("Send Checklist"));
public CheckList2() {
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new GridLayout(0, 1, 1, 1));
for (int i = 0; i < TEXT_FIELD_COUNT; i++) {
JCheckBox checkBox = new JCheckBox("", true);
// final so can use within item listener
final JTextField textField = new JTextField(20);
textField.setEnabled(false);
fields.add(textField);
checkBox.addItemListener(itemEvent -> {
// set textfield enabled based on checkbox state
textField.setEnabled(itemEvent.getStateChange() == ItemEvent.DESELECTED);
});
JPanel rowPanel = new JPanel();
rowPanel.add(checkBox);
rowPanel.add(Box.createHorizontalStrut(3));
rowPanel.add(textField);
checkPanel.add(rowPanel);
}
setLayout(new BorderLayout());
add(checkPanel, BorderLayout.CENTER);
add(sendBtn, BorderLayout.PAGE_END);
}
private class SendAction extends AbstractAction {
public SendAction(String name) {
super(name);
int mnemonic = name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
for (JTextField jTextField : fields) {
System.out.println(jTextField.getText());
}
System.out.println();
}
}
private static void createAndShowGui() {
CheckList2 mainPanel = new CheckList2();
JFrame frame = new JFrame("CheckList2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Why wont my simon game work and what do i need to do so it works

Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}

JPanel doesn't react to MouseEvents?

I'm trying to create a "Tic Tac Toe" game. I've chosen to create a variation of JPanel to represent each square. The class beneath represents one of 9 panels that together make up my game board.
Now the problem I'm having is that when I click the panel a 'X' should be displayed inside of the panel, but nothing happens. I'd very much appreciate it if someone steered me in the right direction.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToePanel extends JPanel implements MouseListener {
private boolean isPlayer1Turn = true;
private boolean isUsed = false;
private JLabel ticTacLbl = new JLabel();
public TicTacToePanel() {
setBorder(BorderFactory.createLineBorder(Color.BLACK));
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
if (!isUsed) {
if (isPlayer1Turn) {
ticTacLbl.setForeground(Color.red);
ticTacLbl.setText("X");
add(ticTacLbl, 0);
isUsed = true;
} else {
ticTacLbl.setForeground(Color.blue);
ticTacLbl.setText("O");
add(ticTacLbl, 0);
isUsed = true;
}
} else {
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, new TicTacToePanel());
}
}
EDIT:
I simply added my label component in the constructor of my TicTacToePanel so that I no longer have to call revalidate() and I'm not adding components during runtime.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToePanel extends JPanel implements MouseListener{
private boolean isPlayer1Turn = true;
private boolean isUsed = false;
private JLabel ticTacLbl = new JLabel();
public TicTacToePanel(){
add(ticTacLbl, 0);
setBorder(BorderFactory.createLineBorder(Color.BLACK));
addMouseListener(this);
}
public void mouseClicked(MouseEvent e){
}
public void mousePressed(MouseEvent e){
if (!isUsed) {
if (isPlayer1Turn) {
ticTacLbl.setForeground(Color.red);
ticTacLbl.setText("X");
isUsed = true;
} else {
ticTacLbl.setForeground(Color.blue);
ticTacLbl.setText("O");
isUsed = true;
}
}
else{
}
}
public void mouseReleased(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public static void main(String[] args){
JOptionPane.showMessageDialog(null, new TicTacToePanel());
}
}
The GUI constructor:
public TicTacToeGUI(int gameMode){
if(gameMode == 0){
amountOfPanels = 9;
TicTacToePanel[] panelArr = new TicTacToePanel[amountOfPanels];
add(gamePanel, new GridLayout(3, 3));
setPreferredSize(new Dimension(100, 100));
for(int i = 0; i < amountOfPanels; i++){
panelArr[i] = new TicTacToePanel();
gamePanel.add(panelArr[i]);
}
}
else if(gameMode == 1){
amountOfPanels = 225;
TicTacToePanel[] panelArr = new TicTacToePanel[amountOfPanels];
add(gamePanel, new GridLayout(15, 15));
setPreferredSize(new Dimension(500, 500));
for(int i = 0; i < amountOfPanels; i++){
panelArr[i] = new TicTacToePanel();
gamePanel.add(panelArr[i]);
}
}
}
public static void main(String[] args){
JOptionPane.showMessageDialog(null, new TicTacToeGUI(0));
}
}
When you add/remove components at runtime, always call revalidate() afterwards. revalidate() makes the component refresh/relayout.
So just call revalidate() after you add the label and it will work.
If you're goal is to create a Tic Tac Toe game, then you may wish to re-think your current strategy of adding components to the GUI on the fly. Much better would be to create a grid of components, say of JLabel, and place them on the JPanel at program start up. This way you can change the pressed JLabel's text and color, and even its Icon if you want to be fancy during program run without having to add or remove components. For example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class TicTacToePanel extends JPanel {
private static final int ROWS = 3;
private static final int MY_C = 240;
private static final Color BG = new Color(MY_C, MY_C, MY_C);
private static final int PTS = 60;
private static final Font FONT = new Font(Font.SANS_SERIF, Font.BOLD, PTS);
public static final Color X_COLOR = Color.BLUE;
public static final Color O_COLOR = Color.RED;
private JLabel[][] labels = new JLabel[ROWS][ROWS];
private boolean xTurn = true;
public TicTacToePanel() {
setLayout(new GridLayout(ROWS, ROWS, 2, 2));
setBackground(Color.black);
MyMouse myMouse = new MyMouse();
for (int row = 0; row < labels.length; row++) {
for (int col = 0; col < labels[row].length; col++) {
JLabel label = new JLabel(" ", SwingConstants.CENTER);
label.setOpaque(true);
label.setBackground(BG);
label.setFont(FONT);
add(label);
label.addMouseListener(myMouse);
}
}
}
private class MyMouse extends MouseAdapter {
#Override // override mousePressed not mouseClicked
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
String text = label.getText().trim();
if (!text.isEmpty()) {
return;
}
if (xTurn) {
label.setForeground(X_COLOR);
label.setText("X");
} else {
label.setForeground(O_COLOR);
label.setText("O");
}
// information to help check for win
int chosenX = -1;
int chosenY = -1;
for (int x = 0; x < labels.length; x++) {
for (int y = 0; y < labels[x].length; y++) {
if (labels[x][y] == label) {
chosenX = x;
chosenY = y;
}
}
}
// TODO: check for win here
xTurn = !xTurn;
}
}
private static void createAndShowGui() {
TicTacToePanel mainPanel = new TicTacToePanel();
JFrame frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}

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