How to add a scrollpane in the frame window - java

I want to add a scrollpane in the frame window or comboPanel.
Below code, the guiFrame.add(scrollpane) is not working, why it is not working?
How can I add the scrollpane to comboPanel or the guiFrame?
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ExtraComboBox {
private int maxFields = 4; // The max number of fields allowed in the dialog
JComboBox fruits[] = new JComboBox[maxFields];
JPanel comboPanel;
JFrame guiFrame;
String[] valOptions3 = { "&" };
String[] valOptions2 = { "|->", "|=>" };
String[] valOptions1 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] valOptions0 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] fruitOptions1 = { "", "Delay1", "Delay2", "Delay3" };
JButton addField;
int count1 = 0;
JLabel dudel[] = new JLabel[maxFields];
JComboBox dude2[] = new JComboBox[maxFields];
String[] valOptions = { "Unknown", "0", "1" };
String[] s = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
private JLabel comboLbl;
public static void main(String[] args) {
new ExtraComboBox();
}
public ExtraComboBox() {
guiFrame = new JFrame();
// make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("ComboBox GUI");
guiFrame.setSize(350, 350);
// The first JPanel contains a JLabel and JCombobox
comboPanel = new JPanel();
addField = new JButton("Add Field");
addField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource().equals(addField)) {
if (count1 < maxFields) {
comboLbl = new JLabel("Select a relation:");
fruits[count1] = new JComboBox<String>(fruitOptions1);
MyItemListener2 actionListener2 = new MyItemListener2(count1);
fruits[count1].addItemListener(actionListener2);
// System.out.println("HI: " + fruits[count1].getParent());
dude2[count1] = new JComboBox<String>();
System.out.println("ADD FIELDS: " + count1);
comboPanel.add(comboLbl);
comboPanel.add(fruits[count1]);
comboPanel.add(dude2[count1]);
guiFrame.validate();
guiFrame.repaint();
count1++;
} else {
System.out.println("You reached the maximum of 4 fields.");
}
}
}
});
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.add(addField);
// The JFrame uses the BorderLayout layout manager.
// Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
// make sure the JFrame is visible
guiFrame.setVisible(true);
}
class MyItemListener2 implements ItemListener {
private int index;
public MyItemListener2(int pIndex) {
super();
index = pIndex;
}
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
System.out.println("COUNTER: " + index);
System.out.println(evt.getItem());
dude2[index].removeAllItems();
switch ((String) evt.getItem()) {
case "Delay1":
for (int i = 0; i < valOptions1.length; i++) {
dude2[index].addItem(valOptions1[i]); // dude1 = new JComboBox(valOptions1);
System.out.println(valOptions1[i]);
}
break;
case "Delay2":
for (int j = 0; j < valOptions2.length; j++) {
System.out.println(valOptions2[j]);
dude2[index].addItem(valOptions2[j]); // dude1 = new JComboBox(valOptions1);
}
break;
case "Delay3":
for (int j = 0; j < valOptions3.length; j++) {
System.out.println(valOptions3[j]);
dude2[index].addItem(valOptions3[j]); // dude1 = new JComboBox(valOptions1);
}
}
}
}
}
}

How can I add the scrollpane to comboPanel or the guiFrame?
You add the comboPanel to the JViewport of the JScrollPane and then you add the scroll pane to the JFrame.
//guiFrame.add(comboPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane( comboPanel );
guiFrame.add(scrollPane, BorderLayout.CENTER);
It is better to add the scrollpane to the CENTER, then it will get all the space available to the frame.

Related

Unable to add keyListeners to buttons

I am trying to create a keyboard GUI with some basic functionalities. The problem that I am running into is within my draw(...){...} function, which highlights the addKeyListener() method, with the error:
The method addKeyListener(KeyListener) in the type Component is not applicable for the arguments (a3_keyboard)
Im not sure what I'm doing wrong. I tried changing my code up with,
getContentPane().addKeyListener(this);
for (JButton button : first) { button.addKeyListener(this); }
for (JButton button : second) { button.addKeyListener(this); }
for (JButton button : third) { button.addKeyListener(this); }
for (JButton button : fourth) { button.addKeyListener(this); }
for (JButton button : fifth) { button.addKeyListener(this); }
But that's throwing me the same error. Full code below:
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class a3_keyboard extends JFrame implements KeyListener {
//input
String input;
//default color
Color defaultColor = new JButton().getBackground();
//main rows of keys
private String rowOne[] = {
"~", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "+", "h"
};
private String rowTwo[] = {
"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"
};
private String rowThree[] = {
"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "'", "Enter"
};
private String rowFour[] = {
"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "?", " ^"
};
private String rowFive[] = {
" ", "<", "v", ">"
};
/** Account for chars with no shift:
** Program toggles Shift key, meaning
** if a user clicks on it, all keys will be
** toggled to their respective shift value. The
** user can tap the shift key again to
** change back to regular value */
private String shiftless[] = {
"1","2","3","4","5","6","7","8","9","0",
"-","=","q","w","e","r","t","y","u","i","o","p",
"[","]","\\","a","s","d","f","g","h","j","k","l",
";","z","x","c","v","b","n","m",",",".","/"
};
//Account for special chars
private String specialChars[] = {
"~", "-", "+", "[", "]", "\\", ";", ".", "?"
};
private JLabel context = new JLabel("Type some text using your keyboard. "
+ "The keys you press will be highlighed and the text will be displayed.\n "
+ "Note: Clicking the buttons with your mouse will not perform any action.")
.setFont(new Font("Verdana",Font.BOLD,14));
//declare rows of buttons
private JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
//ctor
public a3_keyboard() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000,600));
this.setLocation(50,50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
private void __init__body() {
JTextArea body = new JTextArea().setPreferredSize(new Dimension(600, 150));
}
public void __init__panels() {
JPanel top = new JPanel();
JPanel middle = new JPanel();
JPanel bottom = new JPanel();
JPanel contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5,1));
top.add(info, BorderLayout.WEST);
top.add(info, BorderLayout.SOUTH);
middle.setLayout( new BorderLayout());
middle.add(text, BorderLayout.WEST);
middle.add(text, BorderLayout.CENTER);
}
private void __init__() {
//text area
__init__body();
//panels for layout
__init__panels();
pack();
//get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
//create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
//create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
//draw out the rows of buttons
draw(
r1, length_rowOne,
r2, length_rowTwo,
r3, length_rowThree,
r4, length_rowFour,
r5, length_rowFive
);
}
//draw rows of buttons
public void draw(JPanel r1, int s1,
JPanel r2, int s2,
JPanel r3, int s3,
JPanel r4, int s4,
JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowOne[i] = currentButton;
buttons_rowOne[i].addKeyListener(this);
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowTwo[i] = currentButton;
buttons_rowTwo[i].addKeyListener(this);
r1.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowThree[i] = currentButton;
buttons_rowThree[i].addKeyListener(this);
r1.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFour[i] = currentButton;
buttons_rowFour[i].addKeyListener(this);
r1.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowOne[i]);
//account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400,10));
currentButton.setBounds(10, 10, 600, 100);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFive[i] = currentButton;
buttons_rowFive[i].addKeyListener(this);
}
r1.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
}//!draw(...)
//called when a button is pressed
#Override
public void activated(KeyEvent press) {
int index = press.getKeyCode();
input = String.format("%s", index);
}//!activated(...)
//called when a button is released
#Override
public void deactivated(KeyEvent release) {
int index = release.getKeyCode();
input = String.format( "%s"+KeyEvent.getKeyText(keyCode) );
this.setBackground(defaultColor);;
}//!deactivated(...)
//main method
public static void main(Strings[] args) {
new a3_keyboard();
}//!main method
//obtain the JButton’s original background colour before you change its colour
}//!main class
If Im missing something, please let me know and I'll add it to the question.
Edit:
New code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class a3_keyboard extends JFrame implements KeyListener {
//input
String input;
//input body
JTextArea body;
//panels
JPanel top, middle, bottom, contextBox = new JPanel();
//default color
Color defaultColor = new JButton().getBackground();
//main rows of keys
public String rowOne[] = {
"~", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "+", "h"
};
public String rowTwo[] = {
"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"
};
public String rowThree[] = {
"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "'", "Enter"
};
public String rowFour[] = {
"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "?", " ^"
};
public String rowFive[] = {
" ", "<", "v", ">"
};
/** Account for chars with no shift:
** Program toggles Shift key, meaning
** if a user clicks on it, all keys will be
** toggled to their respective shift value. The
** user can tap the shift key again to
** change back to regular value */
public String shiftless[] = {
"1","2","3","4","5","6","7","8","9","0",
"-","=","q","w","e","r","t","y","u","i","o","p",
"[","]","\\","a","s","d","f","g","h","j","k","l",
";","z","x","c","v","b","n","m",",",".","/"
};
//Account for special chars
public String specialChars[] = {
"~", "-", "+", "[", "]", "\\", ";", ".", "?"
};
//declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
//ctor
public a3_keyboard() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000,600));
this.setLocation(50,50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
JTextArea body = new JTextArea();
body.setPreferredSize(new Dimension(600, 150));
}
public void __init__panels() {
JLabel context = new JLabel("Type some text using your keyboard. "
+ "The keys you press will be highlighed and the text will be displayed.\n "
+ "Note: Clicking the buttons with your mouse will not perform any action.");
context.setFont(new Font("Verdana",Font.BOLD,14));
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5,1));
top.add(context, BorderLayout.WEST);
top.add(context, BorderLayout.SOUTH);
middle.setLayout( new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
//text area
__init__body();
//panels for layout
__init__panels();
pack();
//get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
//create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
//create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
//draw out the rows of buttons
draw(
r1, length_rowOne,
r2, length_rowTwo,
r3, length_rowThree,
r4, length_rowFour,
r5, length_rowFive
);
}
//draw rows of buttons
public void draw(JPanel r1, int s1,
JPanel r2, int s2,
JPanel r3, int s3,
JPanel r4, int s4,
JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowOne[i] = currentButton;
buttons_rowOne[i].addKeyListener(this);
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowTwo[i] = currentButton;
buttons_rowTwo[i].addKeyListener(this);
r1.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowThree[i] = currentButton;
buttons_rowThree[i].addKeyListener(this);
r1.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFour[i] = currentButton;
buttons_rowFour[i].addKeyListener(this);
r1.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowOne[i]);
//account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400,10));
currentButton.setBounds(10, 10, 600, 100);
buttons_rowFive[i] = currentButton;
buttons_rowFive[i].addKeyListener(this);
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFive[i] = currentButton;
buttons_rowFive[i].addKeyListener(this);
}
r1.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
}//!draw(...)
// called when a button is pressed
#Override
public void keyPressed(KeyEvent pressed) {
JButton current = (JButton) pressed.getSource();
current.setBackground(Color.GRAY);
body.append(toString(current.getKeyChar()));
}//!keyPressed(...)
// called when a button is released
#Override
public void keyReleased(KeyEvent released) {
JButton current = (JButton) released.getSource();
current.setBackground(defaultColor);
}//!keyReleased(...)
#Override
public void keyTyped(KeyEvent typed) {
JButton current = (JButton) typed.getSource();
}
//main method
public static void main(String[] args) {
new a3_keyboard();
}//!main method
private static final long serialVersionUID = 999;
}//!main class
Edit 2:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class ButtonInPane extends JFrame implements KeyListener {
//redacted, see below
#Override
public void keyPressed(KeyEvent press) {
JButton current = (JButton) press.getSource();
current.setBackground(Color.GRAY);
StringBuilder sb = new StringBuilder();
sb.append(press.getKeyChar());
body.append(sb.toString());
} // !keyPressed(...)
// called when a button is released
#Override
public void keyReleased(KeyEvent release) {
JButton current = (JButton) release.getSource();
current.setBackground(defaultColor);
} // !keyReleased(...)
#Override
public void keyTyped(KeyEvent typed) {
JButton current = (JButton) typed.getSource();
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class
Edit 3:
#Override
public void keyPressed(KeyEvent press) {
Object current = press.getSource().toString();
for (int i = 0; i < 14; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(Color.GRAY);
} else if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(Color.GRAY);
} else if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(Color.GRAY);
} else if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(Color.GRAY);
} else if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(Color.GRAY);
}
}
} // !keyPressed(...)
// called when a button is released
#Override
public void keyReleased(KeyEvent release) {
Object current = release.getSource().toString();
for (int i = 0; i < 14; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(defaultColor);
} else if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(defaultColor);
} else if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(defaultColor);
} else if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(defaultColor);
} else if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(defaultColor);
}
}
} // !keyReleased(...)
#Override
public void keyTyped(KeyEvent typed) {
// Object current = typed.getSource().toString();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 14; i++) {
// if (current == rowOne[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowTwo[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowThree[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFour[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFive[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// }
// }
}
This version puts the keylistener on the correct component. However you now need to redesign this given your new understanding...
Because as the code is right now, the jtext area body simply gets a repeat of the key as you press them. There are several ways you could solve this.
Some of the brute force and others more intricate but elegant. Ping me if you still want help.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ButtonInPane extends JFrame implements KeyListener {
// input
String input;
//context
JLabel context1, context2;
// default color
Color defaultColor = new JButton().getBackground();
// main rows of keys
public String rowOne[] = {
"~",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"+",
"h"
};
public String rowTwo[] = {
"Tab",
"Q",
"W",
"E",
"R",
"T",
"Y",
"U",
"I",
"O",
"P",
"[",
"]",
"\\"
};
public String rowThree[] = {
"Caps",
"A",
"S",
"D",
"F",
"G",
"H",
"J",
"K",
"L",
":",
"'",
"Enter"
};
public String rowFour[] = {
"Shift",
"Z",
"X",
"C",
"V",
"B",
"N",
"M",
",",
".",
"?",
" ^"
};
public String rowFive[] = {
" ",
"<",
"v",
">"
};
/**
* Account for chars with no shift: Program toggles Shift key, meaning if a
* user clicks on it, all keys will be toggled to their respective shift
* value. The user can tap the shift key again to change back to regular
* value
*/
public String shiftless[] = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"=",
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"[",
"]",
"\\",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
";",
"z",
"x",
"c",
"v",
"b",
"n",
"m",
",",
".",
"/"
};
// Account for special chars
public String specialChars[] = {
"~",
"-",
"+",
"[",
"]",
"\\",
";",
".",
"?"
};
// declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
private JTextArea body;
private JPanel top;
private JPanel middle;
private JPanel bottom;
private JPanel contextBox;
// ctor
public ButtonInPane() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(2000, 600));
this.setLocation(50, 50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
body = new JTextArea();
body.setPreferredSize(new Dimension(600, 150));
body.addKeyListener(this);
}
public void __init__panels() {
context1 = new JLabel("Type some text using your keyboard. " +
"The keys you press will be highlighed and the text will be displayed.");
context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
context1.setFont(new Font("Verdana", Font.BOLD, 14));
context2.setFont(new Font("Verdana", Font.BOLD, 14));
top = new JPanel();
top.setSize(new Dimension(500, 500));
middle = new JPanel();
bottom = new JPanel();
contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5, 1));
top.add(context2);
top.add(context1);
middle.setLayout(new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
// text area
__init__body();
// panels for layout
__init__panels();
pack();
// get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
// create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
// create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
// draw out the rows of buttons
draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);
}
// draw rows of buttons
public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowOne[i] = currentButton;
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowTwo[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowTwo[i] = currentButton;
r2.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowThree[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowThree[i] = currentButton;
r3.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowFour[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFour[i] = currentButton;
r4.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowFive[i]);
// account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400, 10));
currentButton.setBounds(10, 10, 600, 100);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFive[i] = currentButton;
}
r5.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
} // !draw(...)
// called when a button is pressed
#Override
public void keyPressed(KeyEvent press) {
StringBuilder sb = new StringBuilder();
sb.append(press.getKeyChar());
body.append(sb.toString());
} // !keyPressed(...)
// called when a button is released
#Override
public void keyReleased(KeyEvent release) {
Object current = release.getSource();
} // !keyReleased(...)
#Override
public void keyTyped(KeyEvent typed) {
Object current = typed.getSource();
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class

Adding new comboboxes Java

I have a problem with Swing interface on java. Explaination: I have a Combobox with 1, 2, 3, 4, 5 items. When an exact item is selected I need to create some more comboboxes the number of which depends on the selected item. So, if number 5 is selected, 5 more comboboxes must appear in the frame. I used ActionListener but it did not work properly. However, the same code but outside Actionlistener works well. What a problem can it be?
public class FrameClass extends JFrame {
JPanel panel;
JComboBox box;
String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox adults = new JComboBox(s);
JComboBox children = new JComboBox(s1);
panel.add(box, BorderLayout.CENTER);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i <= box.getSelectedIndex(); i++) {
panel.add(adults, BorderLayout.WEST);
panel.add(children, BorderLayout.WEST);
}
}
});
add(panel);
}
}
public class MainClass {
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(Color.WHITE);
frame.setVisible(true);
}
}
The problem that you don't inform the layout manager about new elements in your panel.
Here is the correct variant of your action listener:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class FrameClass extends JFrame {
JPanel panel;
JComboBox<String> box;
String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox[] adults = new JComboBox[5];
JComboBox[] children = new JComboBox[5];
for (int i = 0; i < 5; i++) {
adults[i] = new JComboBox<>(s);
children[i] = new JComboBox<>(s1);
}
panel.add(box, BorderLayout.CENTER);
JPanel nested = new JPanel();
add(nested, BorderLayout.EAST);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
nested.removeAll();
nested.setLayout(new GridLayout(box.getSelectedIndex() + 1, 2));
for (int i = 0; i <= box.getSelectedIndex(); i++) {
nested.add(adults[i]);
nested.add(children[i]);
}
getContentPane().revalidate();
getContentPane().repaint();
pack();
}
});
add(panel);
}
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.getContentPane().setBackground(Color.WHITE);
frame.setLocationRelativeTo(null); // center the window
frame.setVisible(true);
}
}

Here is the code for adding an extra combobox item, but the respective comboboxes value is not changing

It is not changing the corresponding combobox value why it is changing the latest combobox value not the respective combobox?
When i run this code, after clicking addfield two times, when i change the first combobox the second combobox value should change not the fourth combobox, this is wrong, what i want is depending on first combobox selection second combobox should be selectable and if third combobox is selected, then the fourth combobox should be selectable.
add Field button adds extra comboboxes in the window, the way it should work is, in the case when the add Field button is pressed twice, i select first combobox, respectively second combobox should be selectable but for some reason, fourth combobox is getting selectable. you will understand the problem better when you run the above code, I have provided the entire code in the description, please help!
package addextraitem;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ExtraComboBox {
int count = 0;
JComboBox fruits[] = new JComboBox[10];;
JPanel comboPanel;
JFrame guiFrame;
//JComboBox dude1;
String[] valOptions3 = {"&"};
String[] valOptions2 = {"|->", "|=>"};
String[] valOptions1 = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
String[] valOptions0 = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
String[] fruitOptions1 = {"", "Delay1", "Delay2", "Delay3"};
String chosenString;
int numPairs1 = valOptions0.length;
JButton addField;
int count1 = 0;
JComboBox[] ComboBox4 = new JComboBox[numPairs1];
JComboBox[] ComboBox5 = new JComboBox[numPairs1];
JComboBox[] ComboBox6 = new JComboBox[numPairs1];
String[] comborel = {"a", "b", "c", "d", "e"};
JLabel lb;
JComboBox dude;
JTextField handle;
String clockOptions1;
JLabel dudel[] = new JLabel[10];
JComboBox dude1[] = new JComboBox[10];
JComboBox dude2[] = new JComboBox[10];;
//JComboBox dude1[] = new JComboBox[10];
String[] valOptions = {"Unknown", "0", "1"};
String [] s = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
int cnt = 0;
int i = 0;
JLabel comboLbl;
JLabel lb1;
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
new ExtraComboBox();
}
public ExtraComboBox()
{
guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("ComboBox GUI");
guiFrame.setSize(350,250);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//The first JPanel contains a JLabel and JCombobox
comboPanel = new JPanel();
addField = new JButton("Add Field");
addField.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == addField) {
count1++;
comboLbl = new JLabel("Select a relation:");
fruits[count1] = new JComboBox(fruitOptions1);
MyItemListener2 actionListener2 = new MyItemListener2();
fruits[count1].addItemListener(actionListener2);
//System.out.println("HI: " + fruits[count1].getParent());
dude2[count1] = new JComboBox();
System.out.println("ADD FIELDS: " + count1);
comboPanel.add(comboLbl);
comboPanel.add(fruits[count1]);
comboPanel.add(dude2[count1]);
guiFrame.revalidate();
guiFrame.validate();
guiFrame.pack();
guiFrame.repaint();
}
}
});
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.add(addField);
//The JFrame uses the BorderLayout layout manager.
//Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
//make sure the JFrame is visible
guiFrame.setVisible(true);
}
class MyItemListener2 implements ItemListener {
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
JComboBox cb = (JComboBox) evt.getSource();
Object item = evt.getItem();
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
System.out.println("COUNTER: " + count1);
System.out.println(evt.getItem());
dude2[count1].removeAllItems();
if(evt.getItem() == "Delay1") {
System.out.println(valOptions1.length);
for(int i = 0; i < valOptions1.length; i++) {
dude2[count1].addItem(valOptions1[i]); //dude1 = new JComboBox(valOptions1);
System.out.println(valOptions1[i]);
}
}
else if(evt.getItem() == "Delay2") {
System.out.println(valOptions2.length);
for(int j = 0; j < valOptions2.length; j++) {
System.out.println(valOptions2[j]);
dude2[count1].addItem(valOptions2[j]); //dude1 = new JComboBox(valOptions1);
}
}
else if(evt.getItem() == "Delay3") {
System.out.println(valOptions3.length);
for(int j = 0; j < valOptions3.length; j++) {
System.out.println(valOptions3[j]);
dude2[count1].addItem(valOptions3[j]); //dude1 = new JComboBox(valOptions1);
}
}
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
// Item is no longer selected
}
}
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ExtraComboBox {
private int maxFields = 4; // The max number of fields allowed in the dialog
JComboBox fruits[] = new JComboBox[maxFields];
JPanel comboPanel;
JFrame guiFrame;
String[] valOptions3 = { "&" };
String[] valOptions2 = { "|->", "|=>" };
String[] valOptions1 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] valOptions0 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] fruitOptions1 = { "", "Delay1", "Delay2", "Delay3" };
JButton addField;
int count1 = 0;
JLabel dudel[] = new JLabel[maxFields];
JComboBox dude2[] = new JComboBox[maxFields];
String[] valOptions = { "Unknown", "0", "1" };
String[] s = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
private JLabel comboLbl;
public static void main(String[] args) {
new ExtraComboBox();
}
public ExtraComboBox() {
guiFrame = new JFrame();
// make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("ComboBox GUI");
guiFrame.setSize(350, 350);
// The first JPanel contains a JLabel and JCombobox
comboPanel = new JPanel();
addField = new JButton("Add Field");
addField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource().equals(addField)) {
if (count1 < maxFields) {
comboLbl = new JLabel("Select a relation:");
fruits[count1] = new JComboBox<String>(fruitOptions1);
MyItemListener2 actionListener2 = new MyItemListener2(count1);
fruits[count1].addItemListener(actionListener2);
// System.out.println("HI: " + fruits[count1].getParent());
dude2[count1] = new JComboBox<String>();
System.out.println("ADD FIELDS: " + count1);
comboPanel.add(comboLbl);
comboPanel.add(fruits[count1]);
comboPanel.add(dude2[count1]);
guiFrame.validate();
guiFrame.repaint();
count1++;
} else {
System.out.println("You reached the maximum of 4 fields.");
}
}
}
});
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.add(addField);
// The JFrame uses the BorderLayout layout manager.
// Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
// make sure the JFrame is visible
guiFrame.setVisible(true);
}
class MyItemListener2 implements ItemListener {
private int index;
public MyItemListener2(int pIndex) {
super();
index = pIndex;
}
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
System.out.println("COUNTER: " + index);
System.out.println(evt.getItem());
dude2[index].removeAllItems();
switch ((String) evt.getItem()) {
case "Delay1":
for (int i = 0; i < valOptions1.length; i++) {
dude2[index].addItem(valOptions1[i]); // dude1 = new JComboBox(valOptions1);
System.out.println(valOptions1[i]);
}
break;
case "Delay2":
for (int j = 0; j < valOptions2.length; j++) {
System.out.println(valOptions2[j]);
dude2[index].addItem(valOptions2[j]); // dude1 = new JComboBox(valOptions1);
}
break;
case "Delay3":
for (int j = 0; j < valOptions3.length; j++) {
System.out.println(valOptions3[j]);
dude2[index].addItem(valOptions3[j]); // dude1 = new JComboBox(valOptions1);
}
}
}
}
}
}
I think this solves your request. I removed any unused code but kept all variablenames. Please chose the names for your variables in a way anyone reading the code knows what the variable is for.
It is pretty obvious you do not know java or any other high programming language. I'd recommend you to learn the basics first before trying to programm fancy stuff.
I hope this helps you

Retriving the String accosiated with a JCheckBox

I have a lottery game problem and I am able to count the number of checked boxes correctly but I do not understand how to get the String number assigned to the JcheckBox. I thought I could use .getText but that did not work. I am not sure if I am using the proper listener.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JLottery2 extends JFrame implements ItemListener {
private String[] lotteryNumbers = { "1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30" };
private JPanel jp1 = new JPanel();
private JPanel jp2 = new JPanel();
private JPanel jp3 = new JPanel(new GridLayout(3, 10, 5, 5));
private JLabel jl1 = new JLabel("The Lottery Game!!!!!");
private JLabel jl2 = new JLabel(
"To play, pick six number that match the randomly selected numbers.");
private FlowLayout layout = new FlowLayout();
private GridLayout gridBase = new GridLayout(3, 1, 5, 5);
private GridLayout grid = new GridLayout(3, 10, 5, 5);
private Font heading = new Font("Palatino Linotype", Font.BOLD, 24);
private Font bodyText = new Font("Palatino Linotype", Font.BOLD, 14);
private Color color1 = new Color(4, 217, 225);
private Color color2 = new Color(4, 225, 129);
private int maxNumber = 6;
private int counter = 0;
private int[] randomNum;
private String[] userPickedNumbers;
Container con = getContentPane();
public JLottery2() {
super("The Lottery Game");
con.setLayout(gridBase);
con.add(jp1);
jp1.setLayout(layout);
jp1.add(jl1);
jl1.setFont(heading);
jp1.setBackground(color1);
con.add(jp2);
jp2.setLayout(layout);
jp2.add(jl2);
jl2.setFont(bodyText);
jp2.setBackground(color1);
con.add(jp3);
jp3.setLayout(grid);
for (int i = 0; i < lotteryNumbers.length; i++) {
JCheckBox checkBox[] = new JCheckBox[lotteryNumbers.length];
checkBox[i] = new JCheckBox(lotteryNumbers[i]);
jp3.add(checkBox[i]);
jp3.setBackground(color2);
checkBox[i].addItemListener(this);
}
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void randNumber() {
randomNum = new int[maxNumber];
for (int i = 0; i < maxNumber; i++) {
randomNum[i] = ((int) (Math.random() * 100) % lotteryNumbers.length + 1);
System.out.println(randomNum[i]);
}
}
public static void main(String[] args) {
JLottery2 frame = new JLottery2();
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED && counter < maxNumber) {
counter++;
System.out.println("add");
System.out.println(counter);
} else if (e.getStateChange() == ItemEvent.DESELECTED
&& counter < maxNumber) {
counter--;
System.out.println("deduct");
System.out.println(counter);
}
if (counter == maxNumber) {
System.out.println("max");
jp3.setVisible(false);
randNumber();
System.out.println(userPickedNumbers);
}
}
}
((JCheckBox)e.getSource()).getText()
works fine for me with your code.

Change JCombobox popup width [duplicate]

This question already has answers here:
How can I change the width of a JComboBox dropdown list?
(7 answers)
Closed 8 years ago.
How can I set a fixed width of a JComboboxs popup-menu that is using GridBagLayout and fill=HORIZONTAL?
One of the things I tried is to just override the getSize() method but dose not work.
public class ComboBoxSize extends JFrame {
public static void main(String args[]) {
// THE COMBOBOX
String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
JComboBox<String> comboBox = new JComboBox<String>(labels) {
public Dimension getSize() {
Dimension d = getPreferredSize();
d.width = 50;
return d;
}
};
comboBox.setMaximumRowCount(comboBox.getModel().getSize());
// ADD COMBOBOX TO PANEL
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(comboBox, c);
// ADD PANEL TO FRAME
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Here is the solution, this worked for me, add this PopupMenuListener to your JComboBox:
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.ComboPopup;
public class CustomComboBoxPopupMenuListener implements PopupMenuListener {
// ==============================================================================
// Members
// ==============================================================================
private int bgTop = 0;
private int bgLeft = 0;
private int bgRight = 0;
private int bgBottom = 0;
// ==============================================================================
// Constructors
// ==============================================================================
public CustomComboBoxPopupMenuListener() {
super();
}
// ==============================================================================
// Methods
// ==============================================================================
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
final JComboBox box = (JComboBox) e.getSource();
final Object comp = box.getUI().getAccessibleChild(box, 0);
if (!(comp instanceof JPopupMenu)) {
return;
}
final JPopupMenu popupMenu = (JPopupMenu) comp;
popupMenu.setBorder(null);
if (popupMenu.getComponent(0) instanceof JScrollPane) {
final JScrollPane scrollPane = (JScrollPane) popupMenu
.getComponent(0);
scrollPane.setBorder(BorderFactory.createEmptyBorder(bgTop, bgLeft,
bgBottom, bgRight));
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
if (popupMenu instanceof ComboPopup) {
final ComboPopup popup = (ComboPopup) popupMenu;
final JList list = popup.getList();
list.setBorder(null);
final Dimension size = list.getPreferredSize();
size.width = Math.max(box.getPreferredSize().width + bgLeft
+ bgRight, box.getWidth());
size.height = Math.min(scrollPane.getPreferredSize().height
+ bgTop + bgBottom, size.height + bgTop + bgBottom);
scrollPane.setPreferredSize(size);
scrollPane.setMaximumSize(size);
}
}
}
}
Example in your code:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ComboBoxSize extends JFrame {
public static void main(String args[]) {
// THE COMBOBOX
String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
JComboBox<String> comboBox = new JComboBox<String>(labels);
comboBox.setMaximumRowCount(comboBox.getModel().getSize());
comboBox.addPopupMenuListener(new CustomComboBoxPopupMenuListener());
// ADD COMBOBOX TO PANEL
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(comboBox, c);
// ADD PANEL TO FRAME
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Source: click here

Categories

Resources