Radio button event handlers - java

I'm having some trouble with a java project. I've made an empty GUI interface, and now I need to add some functionality to it. I'm stuck, however, on how to go about that. The basic layout has 4 radio buttons, Rectangle, Box, Circle, and Cylinder. I have a group panel that has 4 separate panels that each have text boxes with labels for entering height, length, width, and radius. Here's how it looks: GUI layout. Depending on the radio button that is selected, certain boxes that aren't needed should be hidden. For example, if Rectangle is selected, only the boxes for length and width should be visible.
The main frame that will display everything is here:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import java.awt.Font;
public class GUIFrame extends JFrame
{
//private final BorderLayout layout;
private final FlowLayout layout;
private final JLabel lblTitle;
private final JButton btnProc;
public GUIFrame()
{
super("GUI Layout");
Font titleFont = new Font("Verdana", Font.BOLD, 26);
btnProc = new JButton("Click to Process");
lblTitle = new JLabel("Figure Center");
lblTitle.setFont(titleFont);
widthPanel myWidth = new widthPanel();
myWidth.setLocation(0, 400);
lengthPanel myLength = new lengthPanel();
heightPanel myHeight = new heightPanel();
radiusPanel myRadius = new radiusPanel();
radioButtonPanel myButtons = new radioButtonPanel();
//layout = new BorderLayout(3, 2);
layout = new FlowLayout();
JPanel txtGroup = new JPanel();
txtGroup.setLayout(new GridLayout(2, 2));
txtGroup.add(myWidth);
txtGroup.add(myLength);
txtGroup.add(myRadius);
txtGroup.add(myHeight);
setLayout(layout);
add(lblTitle);
add(myButtons);
add(txtGroup);
add(btnProc);
if(myButtons.btnRectangle.isSelected())
{
myHeight.setVisible(false);
myRadius.setVisible(false);
}
}
private class RadioButtonHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent event)
{
}
}
}
I can get this working using if statements, but I'm supposed to be using event handlers and I'm lost on how to code that to get it to work properly.
if it helps, here's the code for the button panel:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import java.awt.GridLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class radioButtonPanel extends JPanel
{
private final JRadioButton btnRectangle;
private final JRadioButton btnBox;
private final JRadioButton btnCircle;
private final JRadioButton btnCylinder;
private final ButtonGroup radioButtonGroup;
private final JLabel label;
private final JPanel radioPanel;
public radioButtonPanel()
{
radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(5,1));
btnRectangle = new JRadioButton("Rectangle", true);
btnBox = new JRadioButton("Box", false);
btnCircle = new JRadioButton("Circle", false);
btnCylinder = new JRadioButton("Cylinder", false);
label = new JLabel("Select A Figure:");
radioPanel.add(label);
radioPanel.add(btnRectangle);
radioPanel.add(btnBox);
radioPanel.add(btnCircle);
radioPanel.add(btnCylinder);
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(btnRectangle);
radioButtonGroup.add(btnBox);
radioButtonGroup.add(btnCircle);
radioButtonGroup.add(btnCylinder);
add(radioPanel);
}
}
And a sample of one of the panels. They all follow the same setup, just different variable names.
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.GridLayout;
public class heightPanel extends JPanel
{
private final JLabel lblHeight;
private final JTextField txtHeight;
private final JPanel myHeight;
public heightPanel()
{
myHeight = new JPanel();
myHeight.setLayout(new GridLayout(2,1));
lblHeight = new JLabel("Enter Height:");
txtHeight = new JTextField(10);
myHeight.add(lblHeight);
myHeight.add(txtHeight);
add(myHeight);
}
}

The below code should give you a quick introduction of how to use event listener/handler for your button group (JRadioButtons).
but I'm supposed to be using event handlers and I'm lost on how to
code that to get it to work properly.
//add listener to the rectangle button and should be the same for the other `JRadioButtons` but with different `identifiers`.
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRectangle){
//TODO
}
}
});
Depending on the radio button that is selected, certain boxes that
aren't needed should be hidden. For example, if Rectangle is selected,
only the boxes for length and width should be visible.
//To hide JTextFields use
void setVisible(boolean visible) method. You should pass false as the argument to the method if you want to hide the JTextField.
Example:
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRectangle){
TextFieldName.setVisible(false); // set the textfields that you want to be hidden once the Rectangle button is chosen.
}
}
});

Related

Java GUI ButtonHandler issue

I'm not sure what exactly I am doing wrong but I keep getting an error with the ButtonHandler. I have a GUI class and a GUI Test class. The GUI class is the first one and the GUI_Test class is at the bottom. I am using NetBeans IDE 11.0. Everything else works on here but the ButtonHandler. I believe I followed the directions wrong or something because it just keeps telling me to create a new class for the ButtonHandler or break it up. But neither of those things are what I want.
The checkboxes also will not appear in the output text area when you run it.
package javaapplication20;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class Week3GUI extends JFrame {`
//variables
private JRadioButton radCoffee, radTea;
private JCheckBox chkFootball, chkBasketball, chkBaseball;
private JTextArea txtMessage;
public Week3GUI()
{
//instantiate the GUI components
// this sets 5 rows, 20 columns as default size
txtMessage = new JTextArea(5,20);
radCoffee =new JRadioButton("Coffee");
radTea =new JRadioButton("Tea");
//instantiate checkboxes
chkFootball =new JCheckBox("football");
chkBasketball =new JCheckBox("basketball");
chkBaseball =new JCheckBox("baseball");
//create panel for the radio buttons
JPanel p1 =new JPanel();
JPanel p2 =new JPanel();
//set layout for the panel and add the components
p1.setLayout(new FlowLayout());
p1.add(radCoffee);
p1.add(radTea);
// set layout for the panel and add the components
p2.setLayout(new FlowLayout());
p2.add(chkFootball);
p2.add(chkBasketball);
p2.add(chkBaseball);
//need to group the buttons together
ButtonGroup b =new ButtonGroup();
b.add(radCoffee);
b.add(radTea);
//add event handlers for radio buttons
RBHandler rb =new RBHandler();
radCoffee.addItemListener(rb);
radTea.addItemListener(rb);
//use grid layout for the frame
//1 column, multiple rows
setLayout(new GridLayout(0,1));
//first "row" of the frame is the label
add(new JLabel("Which do you like?"));
//next "row" is the panel p1 with radio buttons
add(p1);
//third "row" is the textfield
add(p2);
// fourth "row" is the textfield
add(txtMessage);
} //end constructor
private class RBHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(radCoffee.isSelected())
txtMessage.setText("You like coffee");
else if(radTea.isSelected())
txtMessage.setText("You like tea");
}
private void processChoices()
{
//"read" the radio buttons first
if(radCoffee.isSelected())
txtMessage.setText("You like\ncoffee");
else if (radTea.isSelected())
txtMessage.setText("You like\ntea");
else
{
JOptionPane.showMessageDialog(null,"Must select a beverage",
"Error",JOptionPane.ERROR_MESSAGE);
return; //do NOT continue this method
}
//now read the check boxes and APPEND to textarea
if(chkFootball.isSelected())
txtMessage.append("\nfootball");
if(chkBasketball.isSelected())
txtMessage.append("\nbasketball");
if(chkBaseball.isSelected())
txtMessage.append("\nbaseball");
}
private class ButtonHandler implements ActionListener
{
ButtonHandler h = new ButtonHandler();
#Override
public void actionPerformed(ActionEvent actionEvent)
{
processChoices();
radCoffee.addActionListener(h);
radTea.addActionListener(h);
chkFootball.addActionListener(h);
chkBaseball.addActionListener(h);
chkBasketball.addActionListener(h);
}
}
}
} //end class
package javaapplication20;
import javax.swing.JFrame;
public class Week3GUI_Test {
public static void main(String[] args)
{
Week3GUI g =new Week3GUI();
g.setSize(300,200);
g.setVisible(true);
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Java Swing Checkboxes in a SplitPane

The current layout I am after is simply a split pane horizonal where on the left side are checkboxes and the right side will be output. I will eventually add a submit button the left side after the user checks all wanted items and I will display the result on the right side. The current issue is that I can't even get the background color to show up and the checkboxes are adding wonky. At certain times I can only see one checkbox in the left panel and I am not sure why, and I also set every container to visible and still not able to see it. I add them in the addBoxes function.
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
public class CheckBox2 extends JFrame {
private ArrayList<JCheckBox> boxes = new ArrayList<JCheckBox>();
JLabel leftLabel;
JLabel rightLabel;
JSplitPane splitPane;
public CheckBox2() {
leftLabel = new JLabel();
rightLabel = new JLabel();
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(leftLabel), new JScrollPane(rightLabel) );
leftLabel.setBackground(Color.BLUE);
rightLabel.setBackground(Color.RED);
leftLabel.setVisible(true);
rightLabel.setVisible(true);
splitPane.setVisible(true);
add(splitPane);
}
void addBoxes() {
int i = 0;
for ( i = 0; i < 1; i++ ) {
add(new JCheckBox("word" + i ) );
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CheckBox2 cb = new CheckBox2();
cb.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cb.setSize(340, 340);
cb.setVisible(true);
cb.addBoxes();
}
}
Start by having a read of Laying Out Components Within a Container and How to Use Split Panes both which contain plenty of examples.
Swing layouts are lazy. This means that unless you purposefully trigger a layout pass, any changes won't be reflected on the UI (until a layout pass is triggered, such as resizing the window or making it visible for the first time).
While you can call revalidate and repaint on the container your are changing, in your case, simply calling setVisible last will have the same desired effect
Thanks, so with that I'm just getting the last checkbox, checkbox 9 to show up but it's not giving split screen or showing color :(
That's because JFrame, by default, uses a BorderLayout, which only allows a single component to be managed at any of the five available positions. Instead, you need to add you checkboxes to one of the containers in the split pane.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
public class CheckBox2 extends JFrame {
private ArrayList<JCheckBox> boxes = new ArrayList<JCheckBox>();
JSplitPane splitPane;
private JPanel leftPanel;
private JPanel rightPanel;
public CheckBox2() {
leftPanel = new JPanel(new GridBagLayout());
rightPanel = new JPanel(new GridBagLayout()) {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, new JScrollPane(rightPanel));
leftPanel.setBackground(Color.BLUE);
rightPanel.setBackground(Color.RED);
add(splitPane);
addBoxes();
}
void addBoxes() {
int i = 0;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (i = 0; i < 10; i++) {
leftPanel.add(new JCheckBox("word" + i), gbc);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CheckBox2 cb = new CheckBox2();
cb.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cb.pack();
cb.setLocationRelativeTo(null);
cb.setVisible(true);
}
}

How to add JPanel from another class to frame

Im trying to figure out how to add a JPanel into my main Frame. However, the Panel is in a different class. Essentially, I need the user to press the start button,once pressed it needs to create an object of a class (this class creates a JPanel) and add to main frame. My issue is that once I press the start button nothing happens.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;
public class Display extends JFrame{
private JPanel right,left,center,south;
private JButton start, stop,car1,car2,car3,car4;
private JTextArea text1,text2;
private TitledBorder title1,title2;
private JLabel label,label2,label3;
private RaceDisplay rd;
private Environment env;
public Display() {
super("CAR GAME");
/* ---------------------------------
* BOARD PANELS
-----------------------------------*/
//right panel uses a different layout
right = new JPanel();
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
right.setBackground(Color.GRAY);
//center panel uses default layout
center = new JPanel();
//left panel uses a different layout
left = new JPanel();
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
left.setBackground(Color.GRAY);
//south panel
south = new JPanel();
south.setBackground(Color.GRAY);
/* ---------------------------------------
* Text area used to diaply the results.
------------------------------------------*/
text1 = new JTextArea();
text2 = new JTextArea();
// ------------>car images to be used in the Car class<------------------
ImageIcon img = new ImageIcon("./images/Car1-small.gif");
ImageIcon img2 = new ImageIcon("./images/car2-small.gif");
ImageIcon img3 = new ImageIcon("./images/car3-small.gif");
ImageIcon img4 = new ImageIcon("./images/car4-small.gif");
ImageIcon imgFlag = new ImageIcon("./images/flag1.png");
ImageIcon imgFlag2 = new ImageIcon("./images/flag2.png");
label2 = new JLabel(imgFlag);
label3 = new JLabel(imgFlag2);
center.add(label3);
label = new JLabel("BEST TEAM EVER RACE GAME");
label.setFont(new Font("Georgia", Font.CENTER_BASELINE, 16));
/* ----------------------------------------------------
* creates the buttons and adds the proper image to them
--------------------------------------------------------*/
car1 = new JButton("BRITISH MOTOR COMPANY",img);
car2=new JButton("FAST AND FURIOUS",img2);
car3=new JButton("SCOOBY GANG",img3);
car4=new JButton("SPEEDY CADDY",img4);
start=new JButton("START");
stop = new JButton("STOP");
/* ----------------------------------------------------
* creates the title border and adds them to panels
--------------------------------------------------------*/
title1 = new TitledBorder("RESULTS");
title2 = new TitledBorder("CHOOSE YOUR RACER!");
//adds the title borders to the Panels.
right.setBorder(title1);
left.setBorder(title2);
/* ----------------------------------------------------
* This TextArea is added to the right Panel and it where
* the result will be displayed
--------------------------------------------------------*/
text1 = new JTextArea(" ",100,30);
right.add(text1);
text1.setLineWrap(true);
/* ----------------------------------------------------
* adds the buttons to the proper panels
--------------------------------------------------------*/
south.add(start);
south.add(stop);
left.add(car1);
left.add(car2);
left.add(car3);
left.add(car4);
left.add(label);
left.add(label2);
/* ----------------------------------------------------
* adds the panels to the main Frame at proper location
--------------------------------------------------------*/
add(right,BorderLayout.EAST);
add(left,BorderLayout.WEST);
add(south,BorderLayout.SOUTH);
add(center,BorderLayout.CENTER);
/* -------------------------------------------------
* Gives actions to the buttons
---------------------------------------------------- */
car1.addActionListener(new Car1Button());
car2.addActionListener(new Car2Button());
car3.addActionListener(new Car3Button());
car4.addActionListener(new Car4Button());
start.addActionListener(new Start());
/* ----------------------------------------------------
* sets up the main frame's components
--------------------------------------------------------*/
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1900,700);
setVisible(true);
}//end of constructor
/**
*
*/
private class Start implements ActionListener{
public void actionPerformed(ActionEvent event){
rd = new RaceDisplay();
add(rd);
}
}
This is the other class where the panel is created.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class RaceDisplay extends JPanel implements ActionListener{
private Image img1,img2,img3,img4;
private int velX;
private int x;
private Timer tm;
private Environment env;
private Car car;
public RaceDisplay(){
tm = new Timer(30,this);
x=0;
//velX=car.getSpeed();
velX=x;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon car1 = new ImageIcon("./images/Car1-small.gif");
ImageIcon car2 = new ImageIcon("./images/car2-small.gif");
ImageIcon car3 = new ImageIcon("./images/car3-small.gif");
ImageIcon car4 = new ImageIcon("./images/car4-small.gif");
img1 = car1.getImage();
img2 = car2.getImage();
img3= car3.getImage();
img4= car4.getImage();
g.drawImage(img1,x,100,null);
g.drawImage(img2,x,200,null);
g.drawImage(img3,x,300,null);
g.drawImage(img4,x,400,null);
tm.start();
}
//method runs the images from left to right
public void actionPerformed(ActionEvent e) {
x = x+velX;
if(x>=600){
x=0;
x=x+velX;
// // this.wait();
// } catch (InterruptedException ex) {
// Logger.getLogger(RaceDisplay.class.getName()).log(Level.SEVERE, null, ex);
// }
repaint();
}
repaint();
}
public int getX(){
return x;
}
}
When you add a component to a visible GUI the basic code is:
panel.add(...);
panel.revalidate(); // to invoke the layout manager
panel.repaint();
What exactly do you want? I mean you want the added cars to start running??? for that case you need to write a thread. your start button works perfectly.

How to hide a Text Field when a radio button is selected/not selected?

I'm writting a program to encript data. It has a JTextArea to edit text, but I want to choose if I save it encripted or in plain text. For this I created a JDialog that appears when the save button is clicked. It contains two radio buttons: one to save the data encripted and the other to save in plain text. In the middle of them there is a JPasswordField requesting the key of the encription.
My question is if there is a simple way of making the TextField not useable and half transparent, when the option to save encripted is not selected. Or, if there isn't a simple way of doing it, a way to hide the TextArea. I tryed using a ChangeListener on the radio button but it isn't working. Here is my code:
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class StackOverflowVersion extends JFrame {
public static JFrame frame;
public StackOverflowVersion() {
dialogoCriptografar();
System.exit(EXIT_ON_CLOSE);
}
public void dialogoCriptografar(){
final ButtonGroup bGroup = new ButtonGroup();
JRadioButton[] buttons = new JRadioButton[2];
final JPasswordField passwordField = new JPasswordField(20);
// create the raio bunttons
buttons[0] = new JRadioButton("Encript document before saving");
buttons[1] = new JRadioButton("Just save it");
//ad them to the ButtonGroup
bGroup.add(buttons[0]);
bGroup.add(buttons[1]);
// select the option to encript
buttons[0].setSelected(true);
//creates a panel with the radio buttons and a JPasswordField
final JPanel box = new JPanel();
JLabel descricao = new JLabel("Choose an option to save:");
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
box.add(descricao);
box.add(buttons[0]);
box.add(passwordField);
box.add(buttons[1]);
// creates the dialog
final JDialog dialogo = new JDialog(frame, "Storage options", true);
dialogo.setSize(275,125);
dialogo.setLocationRelativeTo(frame);
dialogo.setResizable(false);
dialogo.add(box);
dialogo.setVisible(true);
/* Doesn't work:
buttons[0].addChangeListener(new ChangeListener(){
boolean visivel = true;//ele começa visivel
public void stateChanged(ChangeEvent event){
if(visivel){
box.remove(password);
SwingUtilities.updateComponentTreeUI(dialogo);
dialogo.revalidate();
dialogo.repaint();
visivel = false;
}
else{
box.add(password);
SwingUtilities.updateComponentTreeUI(dialogo);
dialogo.revalidate();
dialogo.repaint();
SwingUtilities.updateComponentTreeUI(dialogo);
visivel = true;
}
}
});
*/
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new StackOverflowVersion();
frame.setVisible(true);
}
});
}
}
My question is if there is a simple way of making the TextField not useable and half transparent,
Have you tried a simple
textField.setEditable(false);
Or
textField.setEnabled(false);
Observation in your code.
1) Add setVisible at the end after all the UI components' properties, events etc are set.
2) In your case you need a listener for each of the RadioButton.
3) Also I prefer using an ItemListener to a ChangeListener(fires even when mouse is moved over it).
Please check the code below.
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main extends JFrame {
public static JFrame frame;
public Main() {
dialogoCriptografar();
System.exit(EXIT_ON_CLOSE);
}
public void dialogoCriptografar(){
final ButtonGroup bGroup = new ButtonGroup();
final JRadioButton[] buttons = new JRadioButton[2];
final JPasswordField passwordField = new JPasswordField(20);
// create the raio bunttons
buttons[0] = new JRadioButton("Encript document before saving");
buttons[1] = new JRadioButton("Just save it");
//ad them to the ButtonGroup
bGroup.add(buttons[0]);
bGroup.add(buttons[1]);
// select the option to encript
buttons[0].setSelected(true);
//creates a panel with the radio buttons and a JPasswordField
final JPanel box = new JPanel();
JLabel descricao = new JLabel("Choose an option to save:");
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
box.add(descricao);
box.add(buttons[0]);
box.add(passwordField);
box.add(buttons[1]);
// creates the dialog
final JDialog dialogo = new JDialog(frame, "Storage options", true);
dialogo.setSize(275,125);
dialogo.setLocationRelativeTo(frame);
dialogo.setResizable(false);
dialogo.add(box);
// Doesn't work:
buttons[0].addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
if(buttons[0].isSelected()) {
passwordField.setVisible(true);;
//SwingUtilities.updateComponentTreeUI(dialogo);
// System.out.println("asdasd");
box.revalidate();
box.repaint();
}
}
});
buttons[1].addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("a");
if(buttons[1].isSelected()) {
passwordField.setVisible(false);;
//System.out.println("asdasd");
//SwingUtilities.updateComponentTreeUI(dialogo);
box.revalidate();
box.repaint();
}
}
}); //
dialogo.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new Main();
frame.setVisible(true);
}
});
}

Hide left/right component of a JSplitPane (or different layout)

At the moment I write a little client application. I have a window with a JTextArea (Display area for the server output) and a user-list.
My plan is to show/hide this user-list over a menu item, but I don't know how. My ideas:
Use a BorderLayout: Without a JScrollPane for the list. It works, but I cannot change the width of the user-list (Because BorderLayout.WEST and BorderLayout.EAST ignore the width)
Use a BorderLayout with a JScrollPane for the user list and show/hide the JScrollPane -> Does not work, don't ask me why...anyway, this way is not a nice solution
Use a JSplitPane, set the resize weight to 0.9. When the user-list should disappear, I minimize the right component (aka the user list) -> How ?
My code at the moment:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
public class SplitPaneTest extends JFrame implements ActionListener
{
private JSplitPane splitPane;
private JTextArea textDisplay;
private JList<String> listUser;
private JScrollPane scrollTextDisplay;
private JScrollPane scrollListUser;
private JCheckBox itemShowUser;
public static void main(String[] args)
{
new SplitPaneTest();
}
public SplitPaneTest()
{
setTitle("Chat Client");
setMinimumSize(new Dimension(800, 500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textDisplay = new JTextArea();
listUser = new JList<>();
DefaultListModel<String> modelUser = new DefaultListModel<>();
listUser.setModel(modelUser);
modelUser.addElement(new String("User 1"));
modelUser.addElement(new String("User 2"));
modelUser.addElement(new String("User 3"));
scrollTextDisplay = new JScrollPane(textDisplay);
scrollListUser = new JScrollPane(listUser);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setLeftComponent(scrollTextDisplay);
splitPane.setRightComponent(scrollListUser);
splitPane.setResizeWeight(0.9);
setContentPane(splitPane);
JMenuBar menubar = new JMenuBar();
JMenu menuWindow = new JMenu("Window");
itemShowUser = new JCheckBox("Show user list");
itemShowUser.addActionListener(this);
itemShowUser.setSelected(true);
menuWindow.add(itemShowUser);
menubar.add(menuWindow);
setJMenuBar(menubar);
setVisible(true);
}
public boolean isUserListEnabled()
{
return itemShowUser.isSelected();
}
public void setUserListEnabled(boolean status)
{
scrollListUser.setVisible(status);
}
#Override
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == itemShowUser)
{
boolean status = isUserListEnabled();
setUserListEnabled(status);
}
}
}
And the result is:
And with hidden JScrollPane scrollListUser:
Can anybody give me a tipp ? The user-list is still visible ( I thought the JSplitPane would repaint..) .I come from Qt (C++) and in Qt I could use a dock widget - but Swing does not have one and to use third libs....I don't know - maybe there is a solution.
Looks like the splitPane can't handle invisible components well - a way out is to add/remove the scrollPane as appropriate:
public void setUserListEnabled(boolean status)
{
splitPane.setRightComponent(status ? scrollListUser : null);
splitPane.revalidate();
}

Categories

Resources