how to afect jlabel by changing different combobox values - java

I'm having some trouble using two comboboxes to affect the state of one item. Each combo box has a value between 1 and 99, I'm trying to change the values in each, combine them, then display this value on a jlabel. So far I can only the first combobox seems to impact the formula. I have simplified it to the following and thanks for any help :)
private int value1int, value2int;
value1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ex)
{
if (ex.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int value1int = (Integer)ex.getItemSelectable().getSelectedObjects()[0];
}
}
});
value2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent exs)
{
if (exs.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int value2int = (Integer)exs.getItemSelectable().getSelectedObjects()[0];
}
}
});
overallValue2.setText((Integer.toString(value1int + value2int)));
overallValue2.revalidate();

you have to do something like that:
public class GUI extends JFrame ...
private int labelVal;
...
// combobox events - The same code to both comboboxes must works
public void itemStateChanged(ItemEvent exs)
{
if (exs.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int aux = (Integer)combobox1.getSelectedItem()+(Integer)combobox2.getSelectedItem();
int labelVal= aux;
}
}
Them refresh the screen

Related

Java game involving adjacent JButtons

I'm making a small game involving a grid of JButtons (MxN) and the main premise is to click on buttonA and then on buttonB, coloring buttonB and adjacent buttons of the same color as buttonB with the color of buttonA. I have made it so you are able to choose 3 possible difficulties. The colors are randomly generated. The main problem is getting the colors to change.
This is the method that I call after selecting the difficulty of the game:
public static void gameMechanics(int m, int n) {
final String[] pickedColour = {""};
final String[] placedColour = {""};
JButton[][] picked = new JButton[m][n];
JButton[][] placed = new JButton[m][n];
picked[m][n].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickedColour[0] = picked[m][n].getText();
}
});
placed[m][n].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
placedColour[0] = placed[m][n].getText();
}
});
if (pickedColour[0] == "R" && placedColour[0] != "R") {
placed[m][n].setBackground(Color.RED);
placed[m][n].setText("R");
}
else if (pickedColour[0] == "G" && placedColour[0] != "G") {
placed[m][n].setBackground(Color.GREEN);
placed[m][n].setText("G");
}
else if (pickedColour[0] == "B" && placedColour[0] != "B") {
placed[m][n].setBackground(Color.BLUE);
placed[m][n].setText("B");
}
}
I would consider using JPanels and painting them, using a MouseListener instead.
However, if you're set on using JButtons, try this:
button.setBackground(Color.GREEN);
button.setOpaque(true);
Note that this might not work if you're setting the look and feel using UIManager.
Also, you're doing a ton of extra work to map the color to the button - it could get confusing and cause errors down the road. Instead, you might try creating your own class:
class ColoredButton extends JButton {
private static final long serialVersionUID = 3040767030924461426L;
private Color color;
public ColoredButton(Color c) {
this.color = c;
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeColor();
}
});
}
public void changeColor() {
this.setBackground(this.color);
this.setOpaque(true);
}
}
Now, you can construct a new ColoredButton:
// Now, this button will turn green when clicked
ColoredButton temp = new ColoredButton(Color.GREEN);

How to randomly get item from string array?

I am trying to generate random questions from my String array called Questions. There 10 items inside. I am trying to set the text of JLabel where once the button is click one of the questions from the array will randomly be selected and displayed. However these 2 sections of code doesn't return anyting.
public String getNextQuestion() {
int NextQues = (int)(Math.random()*10);
return Questions[NextQues];}
public void actionPerformed (ActionEvent e) {
if(e.getSource() == Button) {
Hello.setText(Questions[NextQues]);
Don't hardcode the magic number 10 in getNextQuestion(). I would prefer
ThreadLocalRandom over Math.random(). Like,
public String getNextQuestion() {
return Questions[ThreadLocalRandom.current().nextInt(Questions.length)];
}
Then invoke that method in actionPerformed like,
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Button) {
Hello.setText(getNextQuestion());
}
}
You should be calling your method getNextQuestion
OK, you need an actionlistener on your button in order for something to happen. Something like
public String getNextQuestion() {
int NextQues = (int)(Math.random()*10);
return Questions[NextQues];}
// inside main method
...
Button.addActionListener (
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Hello.setText(getNextQuestion());
}
});
...

Populating a JList using a JButton and Populating the JTextField using DoubleClick on the Jlist

I am trying to populate a JList through a button, and then populate the JTextField using DoubleClick on the previously populated Jlist.
Code:
private void extractUsedVariablesActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(arguments.size() > 0)
JOptionPane.showMessageDialog(null, "Please complete the predicates before accessing this");
DefaultListModel lista1 = new DefaultListModel();
for (int i = 0;i<variableList.size();i++)
{
if (!lista1.contains(variableList.get(i)))
{
lista1.addElement(variableList.get(i));
}
}
argVariables_List.setModel(lista1);
revalidate();
repaint();
if (lista1.size()>0){
System.out.println("got here1");
MouseListener mouseListener2 = new MouseAdapter()
{
public void mouseClicked1(MouseEvent mouseEvent2)
{
JList varList = (JList) mouseEvent2.getSource();
if (mouseEvent2.getClickCount() == 2)
{
System.out.println("may be");
int index varList.locationToIndex(mouseEvent2.getPoint());
if (index >= 0)
{
Object o2 = varList.getModel().getElementAt(index);
System.out.println(o2.toString());
}
}
}
};
argVariables_List.addMouseListener(mouseListener2);
}
}
It is working fine till populating the Jlist. But when I try the doubleclick operation and print the text at the clicked index I am not getting any output neither any errors. Please suggest me if I am missing something.
public void mouseClicked1(MouseEvent mouseEvent2)
There is no such method in the MouseListener interface. (note the "1").
Make sure you include #Override in the line above the method and you will get a compiler error when you make a typo.
#Override
public void mouseClicked1(MouseEvent mouseEvent2)

Override method that toggles 'isSelected' in getListCellRendererComponent

I would like to make my own method that controles when a component is 'isSelected'.
I have a JList containing multiple JPanel. The constructing class of the JPanel extends ListCellRenderer<>.
To show that one of the JList-component (the JPanels) is selected i use;
#Override
public Component getListCellRendererComponent(..., boolean isSelected, ...) {
if(isSelected){
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
I would like a method that keeps a selected item 'selected' eventhough I choose to select another. I understand this can be done by holding down CTRL, but .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); does not quite do the trick. I would rather like to select multiple by clicking on them, and deselect by clicking on them.
For this i have worked with the ListSelectionMode, but i cant find a way.
When done the above I would like to implement a method that only selects a component in the list when clicked in a certain area (instead of the whole component which is preset). I have made this method, which returns true if the correct area is clicked, else false. But since I cant figure out how to override the mouseevent that makes the components 'isSelected' this has been tricky.
Here is the code for the method I would like to override the 'isSelected' method;
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent evt) {
if(ActionHandler.mouseClickedPrebuild(evt.getPoint())){
//This code runs if that special place is clicked!
//So now the component should be 'isSelected' or
//deselected if it already was 'isSelected'.
}
}
});
This code is in the constructor of my JList
And the mouseClickedPrebuild method;
public static boolean mouseClickedPrebuild(Point point) {
int index = theJList.locationToIndex(point);
Rectangle bounds = theJList.getCellBounds(index,index);
Point p = bounds.getLocation();
return ( ... long list of greater than & less than ...);
//This gives the certain area which is accepted to return true
I solved the issue!
So I get my view showing by running this line;
// UI Class JScrollPane Custom JList
UIConstructor.listview.setViewportView(new ListView( -insert ArrayList here- ));
Here is my ListView. The custom DefaultListSelectionModel I used to solve my problem was posted by #FuryComptuers right here;
JList - deselect when clicking an already selected item
I had to make a few changes to the code, since the two methods in the selectionModel will run before my mouseevent. I saved the variabels staticly, so instead of running the code in setSelectionInterval I did it inside my mousePressed.
I then could add the boolean isSelected which returns true, if a curtain area within a specific list element is clicked.
public class ListViewd extends JList {
static boolean isSelected;
static Point point;
static boolean gS = false;
static int in0;
static int in1;
#Override
public Dimension getPreferredScrollableViewportSize() {
Dimension size = super.getPreferredScrollableViewportSize();
size.setSize(new Dimension(0,0));
return size;
}
public ListView(ArrayList<System> items) {
DefaultListModel<System> list = new DefaultListModel<System>();
for (System item : items) {
list.addElement(item);
}
this.setSelectionModel(new DefaultListSelectionModel() {
boolean gestureStarted = false;
#Override
public void setSelectionInterval(int index0, int index1) {
gS = gestureStarted;
in0 = index0;
in1 = index1;
gestureStarted = true;
}
#Override
public void setValueIsAdjusting(boolean isAdjusting) {
if (!isAdjusting) {
gestureStarted = false;
}
}
});
ListSelectionModel selectionModel = this.getSelectionModel();
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
point = e.getPoint();
isSelected = ActionHandler.mouseClickedPrebuild(point);
if(!gS && isSelected){
if (isSelectedIndex(in0)) {
selectionModel.removeSelectionInterval(in0, in1);
} else {
selectionModel.addSelectionInterval(in0, in1);
}
}
}
});
setModel(list);
setCellRenderer(new ListModelPrebuild());
}

How to keep the popup menu of a JComboBox open on populating it?

I have a JComboBox on my Panel. One of the popup menu items is 'More' and when I click that I fetch more menu items and add them to the existing list. After this, I wish to keep the popup menu open so that the user realizes that more items have been fetched however, the popup closes. The event handler code I am using is as follows
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == myCombo) {
JComboBox selectedBox = (JComboBox) e.getSource();
String item = (String) selectedBox.getSelectedItem();
if (item.toLowerCase().equals("more")) {
fetchItems(selectedBox);
}
selectedBox.showPopup();
selectedBox.setPopupVisible(true);
}
}
private void fetchItems(JComboBox box)
{
box.removeAllItems();
/* code to fetch items and store them in the Set<String> items */
for (String s : items) {
box.addItem(s);
}
}
I do not understand why the showPopup() and setPopupVisible() methods are not functioning as expected.
add the following line in the fetchItems method
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
box.showPopup();
}
}
If u call selectedBox.showPopup(); inside invokelater also it will work.
overwrite the JCombobox setPopupVisible metod
public void setPopupVisible(boolean v) {
if(v)
super.setPopupVisible(v);
}
jComboBox1 = new javax.swing.JComboBox(){
#Override
public void setPopupVisible(boolean v) {
super.setPopupVisible(true); //To change body of generated methods, choose Tools | Templates.
}
};
I found some simple solution to always keep popup open. It may be useful with some custom JComboBox'es, like the one I have in my project, but is a little hacky.
public class MyComboBox extends JComboBox
{
boolean keep_open_flag = false; //when that flag ==true, popup will stay open
public MyComboBox(){
keep_open_flag = true; //set that flag where you need
setRenderer(new MyComboBoxRenderer()); //our spesial render
}
class MyComboBoxRenderer extends BasicComboBoxRenderer {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (index == -1){ //if popup hidden
if (keep_open_flag) showPopup(); //show it again
}
}
}
}

Categories

Resources