Show the first element in a JComboBox - java

I have a JComboBox with a list of elements. So what the program basically does is user select an element from the combo list and click a button to display the selected element in the text area.
Everything works perfect so far, but the problem is after user click the button I want the combo box to return back to the firs element and display the first element. How can I display the first element of the combo box...????

Try JComboBox#setSelectedIndex(0).

In the action listener you have to reset the selectedIndex of the comboBox to the first position after you have updated the text area with the selected value.
Sample code :
package com.mumz.test.swing;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;
public class JComboBoxTest {
private void init(){
JPanel panel = new JPanel(new BorderLayout());
Object[] values = new String[]{"One","Two","Three"};
final JComboBox comboBox = new JComboBox(values);
panel.add(comboBox, BorderLayout.NORTH);
final JTextArea textArea = new JTextArea(2, 2);
panel.add(textArea, BorderLayout.CENTER);
JButton button = new JButton("Action");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.setText((String) comboBox.getSelectedItem()) ;
comboBox.setSelectedIndex(0);
}
});
panel.add(button, BorderLayout.SOUTH);
JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new JComboBoxTest().init();
}
}

JComboBox implements two methods for set Item
comboBox.setSelectedIndex(int);
comboBox.setSelectedItem(Object);
more in the example

Related

How to show combo box elements by clicking a button?

I'm Using Java Swing. I have kept a Button over a Combo box because for me Coloring button is much easier than Coloring Combo box and I want that when the button is Clicked, all the Combo Box elements should Display. I have kept the combo box and button in Layered Pane and Layout is Absolute Layout.
If it is not possible, how can we change the Background Color of a Combo Box?
Since you didn't provide a minimal runnable example, I went ahead and created this GUI.
Here's the same GUI after I left-clicked the JButton.
As you can see, the JComboBox now has selections.
Oracle has a nifty tutorial, Creating a GUI With Swing, that will teach you how to create a Swing GUI. Skip the Netbeans section.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ComboBoxButton implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ComboBoxButton());
}
private JComboBox<String> comboBox;
#Override
public void run() {
JFrame frame = new JFrame("ComboBox Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton button = new JButton("Click Me");
button.addActionListener(new ButtonListener());
panel.add(button, BorderLayout.BEFORE_FIRST_LINE);
comboBox = new JComboBox<>();
panel.add(comboBox, BorderLayout.CENTER);
return panel;
}
public class ButtonListener implements ActionListener {
private boolean firstTimeSwitch = true;
#Override
public void actionPerformed(ActionEvent event) {
if (firstTimeSwitch) {
String[] selection = { "alpha", "beta", "gamma", "zeta" };
for (int index = 0; index < selection.length; index++) {
comboBox.addItem(selection[index]);
}
firstTimeSwitch = false;
}
}
}
}

How to add non editable text view to a JDialog?

I have a JFrame with a button labelled as "order". When that button is clicked, a dialog box comes up. This dialog box is supposed to show a summary of items that are ordered as a text view. I thought of having a string as a way to view the order, but that did not work out...
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;
import javax.swing.JRadioButton;
public class PizzaOrder3 {
PizzaOrder3() {
JFrame frame = new JFrame();
JButton order = new JButton("Order");
JPanel panel1 = new JPanel();
panel1.add(order);
frame.getContentPane().add(panel1);
panel1.setBounds(350,632,110,40);
panel1.setOpaque(false);
//Action listener for showing summary of the order
order.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JDialog d = new JDialog(frame, "Hello", true);
//Where the coding for text view is meant to go
d.setSize(400, 300);
d.setVisible(true);
}
});
frame.setLayout(null);
frame.setSize(600, 700);
frame.getContentPane().setBackground(new Color(40, 80, 120));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
PizzaOrder3 PizzaOrder3 = new PizzaOrder3();
}
}

java not displaying jpanel in jframe after button press

I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...

How can I make buttons to make square with color?

Write a program that shows a window with three button. Each button has a name like “Red” , “Green” and “Blue”. In this window, there is also a label. The label contains an icon. This icon must be a CompositeIcon where in the beginning is empty. Every time you press on a button you can see a square with the button color like for an example “press blue button -> a blue square appears on the window”.
So far I have this. I have the three buttons with their color name. I every time I press one of the buttons it does not work. What do I need to do?
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionTester{
public static void main(String[] args){
JFrame frame = new JFrame();
final JTextField textField = new JTextField();
JButton RedButton = new JButton("Red");
RedButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SquareIcon red = new SquareIcon(20,Color.RED);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(red);
}
});
JButton GreenButton = new JButton("Green");
GreenButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SquareIcon green = new SquareIcon(20,Color.GREEN);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(green);
}
});
JButton BlueButton = new JButton("Blue");
BlueButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SquareIcon blue = new SquareIcon(20,Color.BLUE);
CompositeIcon ci = new CompositeIcon();
ci.addIcon(blue);
}
});
frame.setLayout(new FlowLayout());
frame.add(RedButton);
frame.add(GreenButton);
frame.add(BlueButton);
frame.add(textField);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
All you need to do is to create one Square Object that you change in the ActionListener like:
final JPanel sqr = new JPanel();
JButton RedButton = new JButton("Red");
RedButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
sqr.setBackground(Color.RED);
}
});
And dont forget to add sqr to the frame
On another note, please avoid using imports like
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
In my project it came down to
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
Some IDEs can sort you imports automaticly so you dont need to bother with the most common imports anymore
the buttons itself work but you never add the compositeicon to your frame. therefore nothing is displayed

How to make radio buttons change text dynamically in Java

I'm fairly new to GUI. I'm trying to make it so that depending on which radio button is selected, a JLabel changes its value. For example, if "id" is selected, it'll display "http://steamcommunity.com/id/" and if "profile" is selected, it'll display "http://steamcommunity.com/profiles/". I have some code up and running and it's nearly complete:
package sgt;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class RadioButtonPrompt extends JPanel
implements ActionListener {
private static final long serialVersionUID = 1L;
static String idString = "ID";
static String profileString ="Profile";
static String type = idString;
public RadioButtonPrompt() {
super(new BorderLayout());
// Create radio buttons.
JRadioButton idButton = new JRadioButton(idString, true);
idButton.setMnemonic(KeyEvent.VK_I);
idButton.setActionCommand(idString);
JRadioButton profileButton = new JRadioButton(profileString);
profileButton.setMnemonic(KeyEvent.VK_P);
profileButton.setActionCommand(profileString);
// Group radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(idButton);
group.add(profileButton);
idButton.addActionListener(this);
profileButton.addActionListener(this);
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(idButton);
radioPanel.add(profileButton);
JPanel textPanel = new JPanel ();
JLabel URL = new JLabel(setJLabelValue());
JTextField text = new JTextField("sampletextfield");
text.setPreferredSize(new Dimension(100, 20));
textPanel.add(URL);
textPanel.add(text);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0));
JButton submit = new JButton("Submit");
submit.setMnemonic(KeyEvent.VK_S);
buttonPanel.add(submit);
add(radioPanel, BorderLayout.LINE_START);
add(textPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
setBorder(BorderFactory.createCompoundBorder());
}
private String setJLabelValue() {
if (type.equals("ID")) {
return "http://steamcommunity.com/id/";
}
return "http://steamcommunity.com/profiles/";
}
public void actionPerformed(ActionEvent e) {
// Returns either "Profile" or "ID"
type = ((JRadioButton)e.getSource()).getText();
System.out.println(type);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Steam Game Tracker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new RadioButtonPrompt();
newContentPane.setOpaque(true); //content panes must be opaque
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();
}
});
}
}
Take a look at this SO thread.
in actionPerformed() you need to textpanel.setText() to whatever you want based on which button was clicked. I'm guessing at the method name, haven't done any UI stuff with Java for a while.

Categories