I am new to Java and couldn't find any answers for my problem that I was able to understand.
I want to make a selected value in my ComboBox change what text is displayed in the textfield.
For example, if the user selects an artist in the combobox, then the artists' albums are displayed in the textfield.
Any help is appreciated. Thanks!
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
String a = (String)jComboBox1.getSelectedItem();
int artists = 0;
switch (artists){
case 0: jTextField1.setText("Take Care, Nothing Was The Same, Views, More Life, Scorpion");
break;
case 1: jTextField1.setText("Stoney, Beerbongs & Bentleys");
break;
case 2: jTextField1.setText("One Love, Listen, Nothing But the Beat");
break;
case 3: jTextField1.setText("Ready for the Weekend, 18 Months, Motion");
break;
case 4: jTextField1.setText("Cole World: The Sideline Story, 2014 Forest Hills Drive, 4 Your Eyez Only");
break;
case 5: jTextField1.setText("My Beautiful Dark Twisted Fantasy, Yeezus, The Life of Pablo, ye");
break;
case 6: jTextField1.setText("Parachutes, a Rush of Blood to the Head, X&Y, Viva La Vida, Mylo Xyloto");
}
}
Here is a full working example:
import java.awt.GridLayout;
import javax.swing.*;
public class ChangeTextViaCheckbox extends JFrame {
public ChangeTextViaCheckbox() {
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 1));
JCheckBox cb1 = new JCheckBox("Checkbox 1");
JCheckBox cb2 = new JCheckBox("Checkbox 2");
JTextField tf = new JTextField();
cb1.addActionListener(e -> tf.setText("CB 1 is active"));
cb2.addActionListener(e -> tf.setText("CB 2 is active"));
add(cb1);
add(cb2);
add(tf);
}
public static void main(String[] args) {
ChangeTextViaCheckbox frame = new ChangeTextViaCheckbox();
frame.pack();
}
}
The both ActionListener listen on a performed action. If thats the case, they set a new Text in the JTextField.
But it would be better, if you implement it via JRadioButton and a ButtonGroup. With this there can't be a multiple choice.
Your question is lacking details and examples, you should post the important parts of your code that you've already written, for example I have no idea now what [GUI] API are you using(for example swing or AWT), so I strongly advise you to edit your question and provide more details, but either way I'm going to give you a simple example.
I'm going to assume your using the swing api, but it shouldn't be that different if your using another GUI api (like AWT).
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingExample extends JFrame{
public SwingExample(){
String[] artists = {"artist1","artist2","artist3"};
Map<String,String> albumOfArtists = new HashMap<String,String>();
albumOfArtists.put("artist1","album1");
albumOfArtists.put("artist2","album2");
albumOfArtists.put("artist3","album3");
JComboBox combo1 = new JComboBox<String>(artists);
JTextField field1 = new JTextField();
//You implement an action listener to define what should be done when
//an user performs certain operation. An action event occurs,
//whenever an action is performed by the user. Examples: When the user
//clicks a button, chooses a menu item, presses Enter in a text field.
//add action listener to your combobox:
combo1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String selectedString=(String)combo1.getSelectedItem();
field1.setText(albumOfArtists.get(selectedString));
//for example if you select artist1 then the text displayed in the text field is: album1
}
}
add(combo1);
add(field1);
}
private static void createAndShowGUI() {
JFrame frame = new CreateNewJTextField();
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
You can use switch() for your combobox. I've written a code which has the name defined to combobox as cb1. The getSelectedItem() method is used for cb1. You can define the corresponding command for each case (starting from index 0).
String a = (String)cb1.getSelectedItem();
int i = 0;
switch (i){
case 0:
break;
}
Make sure to end each case with break; or your code will execute repeatedly.
Now if the textfield you're using is t1 then the following code is generalised,
switch (i) {
case 0: t1.setText(<whatever you want to display>);
break;
}
Hope this helps.
Here's the revisited code:
String a = (String)cb1.getSelectedItem();
int i = 0;
switch(i){
case 0: t1.setText("Take Care, Nothing Was The Same, Views, More Life, Scorpion");
// for combobox option Drake index = 0
break;
case 1: t1.setText("Stoney, Beerbongs & Bentleys");
// for combobox option post_malone index = 1
break;
case 2: t1.setText("One Love, Listen, Nothing But the Beat");
// for combobox option david_guetta
break;
}
switch is a selection statement that successively tests the value of an expression against alist of integers or characters constants. When a match is found, the statements associated with that constant are executed. Here, the variable i is the expression(the option you choose from combobox) which is evaluated.
Hope this helps again!
Related
this might be a duplicate of JComboBox popup menu not appearing , but as it is a rather old question and not been active for quite some time, plus all the answers were not solutions, that helped with my problem. Thus I decided to create a new question.
The Problem is as follows:
I got an application of a prior colleque, that does not work at my company anymore. Now I tried adding a JComboBox to a JPanel. The JCombobox is displayed as expected, but it behaves in the same way as described by Seth in his question:
1) The first click on the expand button does nothing. The second click highlights the contents of the box, but the popup still doesn't appear.
2) Once I've clicked the button and given it focus, up/down keystrokes cycle through the entries correctly.
I have broken down the code to what I think is the minimum of needed programming, to have the problem occur. (As one comment in the mentioned question mentioned to provide SSCCE, which never happened).
Now here is the code I can provide:
public static class CreateProjectDialog extends JFrame {
private Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
public CreateProjectDialog() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
int SZ_INCR = 1;
// Passe Fontgröße an Resolution an:
if (size.width > 1920) {
SZ_INCR = 2;
}
// Initialize Glass Layer
final JPanel panelGlass = (JPanel) getGlassPane();
panelGlass.setLayout(null);
panelGlass.setVisible(true);
private static JPanel licBorrowPanel = null;
licBorrowPanel = new JPanel();
licBorrowPanel.setBounds(0, 20, 1000, 500);
licBorrowPanel.setVisible(false);
licBorrowPanel.setBackground(Color.WHITE);
panelGlass.add(licBorrowPanel);
}
public static void main(String[] args) {
hauptFrame = new CreateProjectDialog();
}
public static void licenceBorrowDialog() {
int mainWidth = hauptFrame.getSize().width;
int mainHeight = hauptFrame.getSize().height;
// pick a Date
JComboBox dayList = new JComboBox();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar calToday = Calendar.getInstance();
Date dayToday = calToday.getTime();
int weekDay = calToday.get(Calendar.DAY_OF_WEEK);
String weekDayName = "";
for (int i = 1; i <= 22; i++){
dayToday.setDate(dayToday.getDate()+1);
weekDay = dayToday.getDay();
weekDayName = translateWeekDay(weekDay);
dayList.addItem(i + " day(s) until " + weekDayName + " " + df.format(dayToday));
}
dayList.setOpaque(true);
dayList.setSelectedIndex(2);
dayList.setBounds(mainWidth / 2 - (125*SZ_INCR), (165*SZ_INCR), (250*SZ_INCR), (100*SZ_INCR));
licBorrowPanel.add(dayList);
dayList.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int numberOfDays;
JComboBox dl = (JComboBox)e.getSource();
numberOfDays = dl.getSelectedIndex()+1;
labelSelectedDate.setText("<HTML><BODY><b>Count of days: </b>" + numberOfDays + "</HTML></BODY>");
}
});
}
//Translate weekday int to name
public static String translateWeekDay(int day){
String retDay;
switch (day) {
case 0: retDay = "Monday";
break;
case 1: retDay = "Truesday";
break;
case 2: retDay = "Wednesday";
break;
case 3: retDay = "Thursday";
break;
case 4: retDay = "Friday";
break;
case 5: retDay = "Saturday";
break;
case 6: retDay = "Sunday";
break;
default: retDay = "Invalid day";
break;
}
return retDay;
}
}
I tried popoulating with more items (as proposed by jluzwick) to see, if the DropDown is simply hidden behind anything, but no.
I definitely have never used getRootPane() instead of getContentPane(), as suspected by Sehtim.
There is also JCombobox is not displayed , where the accepted answer is to set the setVisible(true) to the end of the constructor. I tried that and it did not change any behaviour in my case.
The question I need an answer to, is: How do I make the DropDown list visible, to enable the user to easily choose an entry?
Thanks MadProgrammer for the hint regarding the code not compiling - I found a solution and will provide it here for anyone having a similar issue.
The problem was a result of mixing heavy weight and light weight components (awt / swing).
This resulted in the light weight popup being used, which was then probably occluded by other components and thus not visible.
The solution ( if the mix of both heavy and light weight has to stay ) is to disable the light weight popup forcing the application to use a backup popup. This is done by replaceing the following line:
dayList.setSelectedIndex(2);
With this line:
dayList.setLightWeightPopupEnabled (false);
I found the solution here:
http://de.comp.lang.java.narkive.com/t2GPS9vy/jcombobox-poppt-nicht-auf
I have 2 comboboxes and I need to make it so that when certain options are selected from the drop down list, certain results are outputted. How do I associate certain string variables or objects with multiple combobox selections. I'm not asking you to do my homework for me. Just need pointing in the right direction.
public class gui extends JFrame implements ActionListener{
String[] colour1 = {"red", "blue", "green", "orange", "brown","white", "black", "yellow", "purple", "pink"};
String[] colour2 = {"red", "blue", "green", "orange", "brown","white", "black", "yellow", "purple", "pink"};
JComboBox combo1 = new JComboBox(colour1);
JComboBox combo2 = new JComboBox(colour2);
JLabel message = new JLabel();
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(0, 1));
public gui() {
panel.add(combo1);
panel.add(combo2);
panel.add(message);
frame.add(panel);
}
I'm using actionPerformed to catch the users input, and then output specific results. At the moment it only takes the value of one combobox and outputs a string. How do i make it take 2.
public void actionPerformed(ActionEvent e){
if(e.getSource() == combo1){
JCombobox cb = (JComboBox)e.getSource();
String colours = (String) cb.getSelectedItem();
switch(colours){
case "red": message.setText("");
break;
case "blue": message.setText("");
break;
case "green": message.setText("");
break;
case "pink": message.setText("");
break;
case "purple":message.setText("");
break;
case "white": message.setText("");
break;
case "black": message.setText("");
break;
case "brown": message.setText("");
break;
case "orange": message.setText("");
break;
case "yellow": message.setText("");
break;
default: message.setText("");
}
}
}
As it was pointed out in the comments, you probably don't need both arrays. When both combo boxes should contain the same values, then you can pass the same array to both combo boxes.
The actual question seems to be aiming at how to perform a specific action depending on the combination of the selections of two combo boxes.
I think there are two options for this: You could either store the combo boxes as instance variables, or you could store the selections of the combo boxes as instance variables. Since you're already storing the combo boxes as instance variables, this should be the easier one to go here. So you could do something like this:
#Override
public void actionPerformed(ActionEvent e)
{
String color1 = (String)combo1.getSelectedItem();
String color2 = (String)combo2.getSelectedItem();
// Possibly check if either color is 'null' here
if (color1.equals("blue") && color2.equals("yellow"))
{
message.setText("green");
}
...
}
(Note: If you now intend to write a nested switch-statement like
switch(colour1)
{
case "red":
switch(colour2)
{
// 10 cases...
}
break;
// 10 x 10 cases...
}
you should think about a different approach, depending on what you want to do with these colors...)
What you want is display a Value depending on the selected Values of the two comboboxes. Make combo1 and combo2 private fields. Write a private method to respond to the action event of both combo. Switch on combo values. Note that you can access both combo directly because they are class fields
I have a question about making JLabels Copyable. I have a drop down menu which takes the imput and displays it as a JLabel, and the label changes when the menu changes. However, I want to make the JLabel copyable. I have heard this is not possible, so i changed the labels to strings and outputted it as a textarea. But when i do this, the string doesnt change when i select a new choice from the drop down menu. Im new to java so be as descriptive as possible please, thank you.
Here are some bits of my code. I really just need a way to make the JTextArea/JLabel copyable and have it be able to change
String[] players = {"Nearest Player", "All Players", "Random Player"};
JComboBox<String> player = new JComboBox<String>(players);
JLabel playernumb = new JLabel ("#p");
JLabel playerprompt = new JLabel("Target Player:");
JTextPane box = new JTextPane();
public static void main(String[] args) {
mc frame = new mc();
frame.setVisible(true);
}
player.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (e.getSource() == player){
JComboBox temp1 = (JComboBox)e.getSource();
String playertxt = (String)temp1.getSelectedItem();
switch (playertxt){
case "Nearest Player": playernumb.setText("#p");
break;
case "All Players": playernumb.setText("#a");
break;
case "Random Player": playernumb.setText("#r");
break;
default: break;
}
}
}
});
add(playerprompt);
add(player);
box.insertComponent(playernumb);
Just use this code fragment to make it look like a JTextPane look like a JLabel.
JTextPane f = new JTextPane();
f.setContentType("text/html"); // let the text pane know this is what you want
f.setEditable(false); // as before
f.setBackground(null); // this is the same as a JLabel
f.setBorder(null); // remove the border
Courtesy of this question: Selecting text from a JLabel?
First, I am new to programming and this is my first major assignment in java and programming in general so if I am doing some incredibly stupid please tell me so I can correct the bad habit.
Anyway to the problem, I am currently trying to create a gridLayout that has a variable number of rows which will be filled with a label that has text that comes from a file. My problem is specifically on gridLayout were the labels that I do add and are constants seem to be disappearing into one giant cell. So far none of the reasearch I have done has lead to anything so I thought I may as well pose the question.
public void fillTimetablePane(JPanel pane){
int noOfRows = pref.getNoOFPeriods()+1;
pane.setLayout(new GridLayout(noOfRows,4));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
JLabel label = new JLabel();
int i=0;
while (i<4){
switch (i) {
case 0: label.setText("Lesson");
break;
case 1: label.setText("Period");
break;
case 2: label.setText("Room");
break;
case 3: label.setText("Teacher");
break;
}
i++;
pane.add(label);
}
}
here is an image of what happens when I add run the following code:
http://www.freeimagehosting.net/1hqn2
public void fillTimetablePane(JPanel pane){
int noOfRows = pref.getNoOFPeriods()+1;
pane.setLayout(new GridLayout(noOfRows,4));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
//JLabel label = new JLabel(); // from here
int i=0; // V
while (i<4){ // V
JLabel label = new JLabel(); // to here
switch (i) {
case 0: label.setText("Lesson");
break;
case 1: label.setText("Period");
break;
case 2: label.setText("Room");
break;
case 3: label.setText("Teacher");
break;
}
i++;
pane.add(label);
}
}
Ok, why is it not working in your case but works fine in my case? The problem is that you add your label 4 times and change the text inbetween. In a Layout, a single component can only be existing once. So what happens is that when you add your label a second/third/fourth time, its location in the grid will be updated and not added again.
In my case, I actually create a new JLabel in every iteration of the loop and therefore adding a different label to the JPanel.
Hope this is clear enough. Just ask if something is not clear.
You added the same label 4 times. Move the new JLabel inside your while loop
I am creating a hangman game. I made a button A - Z using the GUI Toolbars in Netbeans as follows:.
My problem is, how can I add an actionlistener to all of it. Is it possible to use a loop? If i click the button A, i will get the character 'a' and so on..
Yes it is possible to use a loop, but since your JButtons were created by using NetBeans code-generation, they won't be in an array or collection initially, and so this is something that you'll have to do: create an array of JButton and fill it with the buttons created by NetBeans. Then it's a trivial matter to create a for loop and in that loop add an ActionListener that uses the ActionEvent's actionCommand (as noted above) in its logic.
Having said this, I think that the better solution is to forgo use of the NetBean's GUI builder (Matisse) and instead to create your Swing code by hand. This will give you much greater control over your code and a much better understanding of it as well. For instance, if you do it this way, then in your for loop you can both create your buttons, add the listeners, and add the button to its container (JPanel).
e.g.,
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Foo2 {
public static void main(String[] args) {
JPanel buttonContainer = new JPanel(new GridLayout(3, 9, 10, 10));
List<JButton> letterButtons = new ArrayList<JButton>(); // *** may not even be necessary
for (char buttonChar = 'A'; buttonChar <= 'Z'; buttonChar++) {
String buttonText = String.valueOf(buttonChar);
JButton letterButton = new JButton(buttonText);
letterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
System.out.println("actionCommand is: " + actionCommand);
// TODO fill in with your code
}
});
buttonContainer.add(letterButton);
letterButtons.add(letterButton);
}
JOptionPane.showMessageDialog(null, buttonContainer);
}
}
Well, with some pseudo code, wouldn't this make sence for you?
for(button in bord) {
button.addActionListener(my_actionlistener);
}
Then in your actionlistener you can see which button was pressed
public void actionPerformed(ActionEvent e) {
// button pressed
if ("string".equals(e.getActionCommand()) {
// do something
}
// and so forth
}
You'll need to add the buttons to a list of some kind so you can iterate through them, Netbeans doesn't do this for you when you generate the buttons.
After that, just run a for each loop on the list containing all the buttons. To get the values of the characters just cast the relevant ascii value, which starts at 97 for a lower case a or 65 for an upper case A:
int charNum = 97;
for(Button b : board) {
char charVal = (char)charNum;
charNum++;
//add the action listener
}