hello i am confused in reading values from JComboBox. I want a program that if user click and select any item from JComboBox. It will appear as output. example i choose apple it will appear apple the main problem of this is i have no button of my program so i really need it to click then output here is my code so far .
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class imagebut extends JFrame
{
ImageIcon we = new ImageIcon(getClass().getResource("ban.png"));
ImageIcon wer = new ImageIcon(getClass().getResource("ba.png"));
public static void main(String args [])
{
imagebut w = new imagebut();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(300,300);
w.setVisible(true);
}
String []kwe = {"Convertion","Adv.Calculator","Looping","Remarks","Average","MagicSquare","Calendar","Multiplication"};
JComboBox box = new JComboBox(kwe);
public imagebut()
{
/* JButton converter = new JButton("Convertion");
JButton advancecalc = new JButton("Adv.Calculator");
JButton calc = new JButton("Calculator");
JButton Multiplication = new JButton("Multiplication");
JButton Looping = new JButton("Looping");
JButton Calendar = new JButton("Calendar");
JButton Remarks = new JButton("Remarks");
JButton Average = new JButton("Average");
JButton Magicsq = new JButton("Magic Square");*/
JLabel background = new JLabel(new ImageIcon(getClass().getResource("gif.gif")));
JPanel pan = new JPanel();
box.setBounds(10,10,150,25);
getContentPane().add(background);
background.add(box);
/* background.add(converter);
background.add(calc);
background.add(advancecalc);
background.add(Magicsq);
background.add(Remarks);
background.add(Calendar);
background.add(Average);
background.add(Looping);
background.add(Multiplication);*/
}
}
this is my update so example if i click convertion it will make an Frame for Convertion if Average another frame .
Add ActionListener to your JComboBox component and to like:
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(jComboBox1.getSelectedItem().toString());
}
this will get the selected item from your combo box, it will triggers every item you select from combobox
Seems you need to use ItemListener, for example:
JComboBox box = new JComboBox(kwe);
box.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
System.out.println(((JComboBox)e.getSource()).getSelectedItem());
// other actions
}
}
});
Related
When user push a button (I created), it makes the TextField editable.
First I use if condition in constructor as:
if(button.isSelected()) TextField.isEditable(true); else TextField.isEditable(false);
But, this gives me an error. Then I use the same statement (to give permission to user weather he want to make text editable or not) in a method with parameter ActionEvent in which is another method_implemented by ActionListener. But this also gives error. Code and output before applying action on button is given:
Code is given below
Output
package Radio_Button;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Radio_Buttons extends JPanel{
private JRadioButton bold;
private JRadioButton italic;
private JRadioButton both;
private JRadioButton plain;
private ButtonGroup group;
private JTextField TextField;
private JButton button;
public Radio_Buttons(){
//Declare all radio buttons
plain = new JRadioButton("Plain",false);
bold = new JRadioButton("Bold", false);
italic = new JRadioButton("Italic", false);
both = new JRadioButton("Bold+Italic", false);
//Declare Text Field
TextField = new JTextField("The quick brown fox jumps over the lazy dog.",40);
TextField.setFont(new Font("Chiller", Font.PLAIN, 30));
//For button
button = new JButton("Push to edit");
//Add in panel
add(bold);
add(italic);
add(both);
add(plain);
add(TextField);
add(button);
//Make a family of radiobuttons so they can understand each others.
group = new ButtonGroup();
group.add(bold);
group.add(italic);
group.add(both);
group.add(plain);
RadioListener listener = new RadioListener();
bold.addActionListener(listener);
italic.addActionListener(listener);
plain.addActionListener(listener);
both.addActionListener(listener);
setBackground(Color.yellow);
setPreferredSize(new Dimension(800,500));
}
private class RadioListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int source = 0;
if (bold.isSelected()) {source =Font.BOLD; }
else if (italic.isSelected()) {source = Font.ITALIC; }
else if (both.isSelected()){source = Font.BOLD+Font.ITALIC; }
else {source = Font.PLAIN; }
TextField.setFont(new Font("Chiller", source, 30));
}
}
public static void main (String [] args){
JFrame frame = new JFrame("Quote Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Radio_Buttons panel = new Radio_Buttons();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
First thing first. Spend some time to understand having meaningful "variable" names and Naming Convention. e.g variable name like TextField is a no no.
In your example, TextField is enabled by default itself. Initialize it with "editable" as false like below:
TextField.setEditable(false);
Add listener to your button and change editable of Textflied like below
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TextField.setEditable(true);
}
});
I am creating a program for class where you have a JComboBox and when one option is selected it pops up a window with different options. I have one option that pops up a new window with two buttons on it.
First I'm not sure if I should be using ItemListener or ActionListener for the JComboBox options. Right now I have an ItemListener which I thought would work for just "The Matrix" option but it works for both options and I can't figure out why. I'll post all my code just in case but I'll add stars above and below the specified issue.
Thanks for any help or pointing me in the right direction!
public class MultiForm extends JFrame{
private JComboBox menu;
private JButton bluePill;
private JButton redPill;
private JLabel matrix;
private int matrixSelection;
private static String[] fileName = {"", "The Matrix", "Another Option"};
public MultiForm() {
super("Multi Form Program");
setLayout(new FlowLayout());
menu = new JComboBox(fileName);
add(menu);
*************************************************************************
TheHandler handler = new TheHandler();
menu.addItemListener(handler);
}
private class TheHandler implements ItemListener{
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED) {
menu.setSelectedItem("The Matrix");
menu.getSelectedIndex();
*************************************************************************
//Create a new window when "The Matrix" is clicked in the JCB
JFrame newFrame = new JFrame();
JPanel panel = new JPanel();
newFrame.setLayout(new FlowLayout());
newFrame.setSize(500, 300);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
add(panel, BorderLayout.CENTER);
matrix = new JLabel("<html>After this, there is no turning back. "
+ "<br>You take the blue pill—the story ends, you wake up "
+ "<br>in your bed and believe whatever you want to believe."
+ "<br>You take the red pill—you stay in Wonderland, and I show"
+ "<br>you how deep the rabbit hole goes. Remember: all I'm "
+ "<br>offering is the truth. Nothing more.</html>");
newFrame.add(matrix, BorderLayout.NORTH);
Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
bluePill = new JButton("Blue Pill", bp);
newFrame.add(panel.add(bluePill));
Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
redPill = new JButton("Red Pill", rp);
newFrame.add(panel.add(redPill));
newFrame.setVisible(true);
}
}
}
public static void main(String[] args) {
MultiForm go = new MultiForm();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400, 200);
go.setVisible(true);
}
}
ItemListener and ActionListener will tell when something about the combo box has changed. You then need to ascertain WHAT has changed and take appropriate action
For example...
private class TheHandler implements ItemListener{
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED) {
Object source = event.getSource();
if (source instanceof JComboBox) {
JComboBox cb = (JComboBox)source;
Object selectedItem = cb.getSelectedItem();
if ("The Matrix".equals(selectedItem)) {
// Do the matrix
} else if ("Another Option".equals(selectedItem)) {
// Do another option
}
}
}
}
}
This simply checks what the selectedItem is and takes appropriate action according to what is selected. You could also use selectedIndex instead, which will return a int representing the selected item, but which ever is easier for you.
Have a look at How to Use Combo Boxes for more details
If all you want to know is when a item is selected, you might find a ActionListener simpler, as you don't need to check the state (SELECTED/UNSELECTED), as it only triggers on the selected state change
I am still new to using Swing and creating GUIs in Java. I was working on a simple test code where the color of a button changes to a random color when it is pressed. Although it works, every time I press the button, it minimizes the previous window and opens a new one and they keep piling up. How will I make it so that this does not happen? Does this occur because I am creating an object in the actionPerformed method? The reason why I have made an object there is to link the Swing class with the separate Action class I have made in order to manipulate the button variable.
Therefore, my two questions are:
How can I prevent multiple windows from appearing and instead have them replace each other?
Is there a way to utilize ActionListener within the same class and would it make things easier?
Any help is greatly appreciated!
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class Swing extends JFrame{
private JFrame f;
private JLabel l;
private JButton b;
private JPanel p;
public Swing(){
test();
}
//*
public JFrame getJFrame(){
return f;
}
public JLabel getJLabel(){
return l;
}
public JButton getJButton(){
return b;
}
public JPanel getJPanel(){
return p;
}
//*
public void test(){
// Frame Setup
f = new JFrame("Frame");
f.setVisible(true);
f.setSize(500, 500);
f.setResizable(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
//
// Panel Setup
p = new JPanel();
p.setVisible(true);
//
// Other
b = new JButton("Button");
l = new JLabel("Label");
b.addActionListener(new Action());
//
// Additions
p.add(b);
p.add(l);
f.add(p); // ***
//
}
public static void main(String[] args){
Swing swing = new Swing();
swing.test();
}
}
final class Action implements ActionListener{
public void actionPerformed(ActionEvent e){
Swing swingObject = new Swing(); //
JButton button = swingObject.getJButton(); //
button.setBackground(randomColor());
}
public Color randomColor(){
Random rn = new Random();
ArrayList<Color> color = new ArrayList<Color>();
color.add(Color.BLUE);
color.add(Color.GREEN);
color.add(Color.RED);
color.add(Color.YELLOW);
color.add(Color.PINK);
color.add(Color.CYAN);
color.add(Color.ORANGE);
color.add(Color.MAGENTA);
int s = color.size();
int random = rn.nextInt(s);
return color.get(random);
}
}
From your listener, you're executing
Swing swingObject = new Swing();
This does what it should do: create a new Swing JFrame. You don't want a new JFrame, so don't call its constructor. From the listener, simply get the button that fired the event, and change its color:
JButton button = (JButton) e.getSource();
button.setBackground(randomColor());
You could also pass the button to modify when creating the listener:
class Action implements ActionListener{
private JButton buttonToUpdate;
public Action(JButton buttonToUpdate) {
this.buttonToUpdate = buttonToUpdate;
}
public void actionPerformed(ActionEvent e){
buttonToUpdate.setBackground(randomColor());
}
}
And, to create it:
b = new JButton("Button");
b.addActionListener(new Action(b));
Very new to Java, but I am slowly picking my way through things. So please be kind. I understand most things I've tried so far, and built a version of the following that uses console output, but now I'm trying to make a GUI. I tried the netbeans GUI maker, but it created so much new code that when I tried to pick through it, I got lost. I'm much better at learning by piecing new things together myself, not having an IDE generate a ton of code and then attempt to find where I want to work.
I am trying to build an window that has a list with three choices on the left side, a button in the middle that confirms your choice, and an answer output on the right. Once the button is pressed, the input from the list is read and is converted into a corresponding answer. As of right now, all I get is "We recommend... null" after selecting an option in the list. The button appears to do nothing at the moment.
I have used tutorials, hacked up others' code from online, and referenced a few books, but I'm stuck.
Here is what I have:
package diffguidegui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DiffGuideGUI extends JPanel implements ListSelectionListener {
private JList resultsTabList;
private DefaultListModel listModel;
private static final String recommendString = "Recommend a Option";
private JButton recommendButton;
private String recommendOutput;
final JLabel output = new JLabel("We recommend..." + recommendOutput);
//build list
public DiffGuideGUI () {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("A");
listModel.addElement("B");
//create the list and put it in the scroll pane
resultsTabList = new JList(listModel);
resultsTabList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultsTabList.setSelectedIndex(0);
//listener for user input
resultsTabList.addListSelectionListener(this);
resultsTabList.setVisibleRowCount(2);
JScrollPane listScrollPane = new JScrollPane(resultsTabList);
//build the button at the bottom to fire overall behavior
recommendButton = new JButton(recommendString);
recommendButton.setActionCommand(recommendString);
recommendButton.addActionListener(new RecommendListener());
//create a panel that uses Boxlayout for the button
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(recommendButton);
//create a panel that uses Boxlayout for the label
JPanel outputPane = new JPanel();
outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.LINE_AXIS));
outputPane.add(output);
add(listScrollPane, BorderLayout.WEST);
add(buttonPane, BorderLayout.CENTER);
add(outputPane, BorderLayout.EAST);
}
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
}
}
public void valueChanged(ListSelectionEvent e) {
if(e.getValueIsAdjusting() == false) {
if(resultsTabList.getSelectedIndex() == -1) {
recommendButton.setEnabled(false);
} else {
recommendButton.setEnabled(true);
}
}
}
//Create GUI and show it
private static void createAndShowGUI() {
JFrame frame = new JFrame("Recommend Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create and set up content pane
JComponent newContentPane = new DiffGuideGUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The button appears to do nothing at the moment.
It does something. It calculates the value for your recommendOutput varable. But you never output this value.
try the following:
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
System.out.println(recommendOutput); // <-###################
}
}
This should print the value to stdout
To put the value into your label try this instead:
output.setText(recommendOutput);
where do you set the text for the JLabel? It says "We recommend NULL" because recommenedOutput is null when the object is created. I dont see
output.setText("We recommend "+value) anywhere. You probably need output.invalidate() also. Try putting setText(String text)/invalidate() in the RecommendListener.actionPerformed() method.
output.setText("We recommend A");
output.invalidate();
Currently working on a school project in which I am making a wheel of fortune replica in Java. I have a panel of JButtons within a class called buttonPanel, and a separate class, wheelGUI, which acts as the class that the program runs through. What I want to happen is when the JButton spin is pressed on the GUI, it assigns a random value from String[] wheelStuff to a String, spinValue,using the method spinWheel which acts as the parameter for the JTextField results, and then displays that random value on the Cyan box in the GUI. In non-technical terms, when the button spin is pressed, display a random value in the Cyan box which acts as the current players' spin value. Here is the code for the class buttonPanel
package wheelOfFortune;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class buttonPanels extends JPanel
implements ActionListener
{
private JButton spin, solve, buyVowel, guess, reset, end, cont;
Color yungMoney = new Color(0, 180, 100);
private static String[] wheelStuff = new String[]{"Bankrupt", "Lose a Turn", "$5000", "$600", "$500", "$300", "$800", "$550", "$400", "$900", "$350", "$450", "$700"};
public buttonPanels()
{
setBackground(yungMoney);
spin = new JButton("Spin!");
spin.addActionListener(this);
solve = new JButton("Solve the Puzzle");
solve.addActionListener(this);
buyVowel = new JButton("Buy a Vowel");
buyVowel.addActionListener(this);
guess = new JButton("Guess a Letter");
guess.addActionListener(this);
reset = new JButton("Reset");
reset.addActionListener(this);
cont = new JButton("Continue");
cont.addActionListener(this);
JPanel buttonPanel = new JPanel(new GridLayout(3, 1, 5, 5));
buttonPanel.setPreferredSize(new Dimension(300,380));
buttonPanel.setBackground(yungMoney);
buttonPanel.add(spin);
buttonPanel.add(guess);
buttonPanel.add(buyVowel);
buttonPanel.add(solve);
buttonPanel.add(cont);
buttonPanel.add(reset);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
JButton b = (JButton)e.getSource();
b.addActionListener(this);
if(b==spin)
{
wheelGUI.spinWheel(wheelStuff);
}
repaint();
}
}
And here is the code for the main class, wheelGUI
package wheelOfFortune;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;
public class wheelGUI extends JFrame implements ActionListener {
private playerPlate player1, player2, player3;
Color yungMoney = new Color(0, 180, 100);
private String fileName = "M:/wheelOfFortune/src/wheelOfFortune/img/wheel1.png";
private String cat;
private static String spinValue = "";
private static String[] wheelStuff = new String[]{"Bankrupt", "Lose a Turn", "$5000", "$600", "$500", "$300", "$800", "$550", "$400", "$900", "$350", "$450", "$700"};
private static JTextField results;
public wheelGUI() {
super("Butt Stuff!");
ImageIcon i = new ImageIcon(fileName);
JLabel picture = new JLabel(i);
player1 = new playerPlate("Garrett", Color.RED);
player2 = new playerPlate("Jonny", Color.YELLOW);
player3 = new playerPlate("Robert", Color.BLUE);
buttonPanels buttons = new buttonPanels();
letterBoard letters = new letterBoard();
catBox category = new catBox(cat);
inputField input = new inputField();
Box wall = Box.createHorizontalBox();
wall.add(player1);
wall.add(Box.createHorizontalStrut(5));
wall.add(player2);
wall.add(Box.createHorizontalStrut(5));
wall.add(player3);
JPanel result = new JPanel();
result.setBackground(yungMoney);
JTextField results = new JTextField(spinValue);
results.setBackground(Color.CYAN);
results.setHorizontalAlignment(JTextField.CENTER);
results.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
results.setPreferredSize(new Dimension(150,100));
results.setFont(new Font("Impact", Font.PLAIN, 28));
results.setEditable(false);
result.add(results);
Box catInput = Box.createVerticalBox();
catInput.add(category);
catInput.add(Box.createVerticalStrut(50));
catInput.add(result);
catInput.add(Box.createVerticalStrut(100));
catInput.add(input);
Container c = getContentPane();
c.setBackground(yungMoney);
c.add(buttons, BorderLayout.EAST);
c.add(wall, BorderLayout.SOUTH);
c.add(letters, BorderLayout.NORTH);
c.add(picture, BorderLayout.WEST);
c.add(catInput, BorderLayout.CENTER);
}
public static String spinWheel(String[] wheelStuff)
{
Random rnd = new Random();
wheelStuff[rnd.nextInt(wheelStuff.length)] = spinValue;
return spinValue;
}
public static void main(String[] args) {
wheelGUI window = new wheelGUI();
window.setBounds(50, 50, 1024, 768);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
// logic for any additional panels. other logics should be in individual
// classes.
}
}
Thanks for your help! Note: all of the code in wheelGUI that isn't related to something previously stated can be ignored, it's from various other classes.
The use of static fields in this manner is not recommended.
Instead, the buttonsPanel should be taking a reference of the wheelGUI. This will allow the buttonsPanel to call the required methods on the wheelGUI when it needs to.
A better solution would be to use a model which can sit between the two UIs and model the logic, firing events as parts of the model change
Your primary problem is your shadowing the results textfield. That is, you've declared and class level, static field and then redeclared it within your constructor
Change the following line in your wheelGUI constructor
JTextField results = new JTextField(spinValue);
To
results = new JTextField(spinValue);
This will mean when you set the text on the results field, you will be setting the value of the correct instance of the field.