JTextField not editing JTextInput - java

I'm trying to make a simple program where there is a text input field and a label, and when you input something to the field it stores the input as "testInput" and changes the label to that text. I'm using Eclipse's Window Builder plugin for this, and it has worked fine before. What happens now is it will take the text in, but wont send it back out to the jLabel. Here is my code:
package interest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestWin {
String testInput;
private JFrame frame;
private JTextField txtTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestWin window = new TestWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestWin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
txtTest = new JTextField();
//Change label when enter is pressed
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
txtTest.setText(testInput);
}
});
txtTest.setText("test");
GridBagConstraints gbc_txtTest = new GridBagConstraints();
gbc_txtTest.insets = new Insets(0, 0, 5, 0);
gbc_txtTest.fill = GridBagConstraints.HORIZONTAL;
gbc_txtTest.gridx = 5;
gbc_txtTest.gridy = 1;
frame.getContentPane().add(txtTest, gbc_txtTest);
txtTest.setColumns(10);
JLabel lblTest = new JLabel("test");
GridBagConstraints gbc_lblTest = new GridBagConstraints();
gbc_lblTest.gridx = 5;
gbc_lblTest.gridy = 4;
frame.getContentPane().add(lblTest, gbc_lblTest);
}
}
I'm sure I'm making a really simple mistake, so any help is appreciated!

Put
JLabel lblTest = new JLabel("test");
at the begining of initialize() (or anywhere above txtTest.addActionListener...), and then replace
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
txtTest.setText(testInput);
}
});
for
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
lblTest.setText(testInput); //This line was changed.
}
});

Related

JTextArea in GridBagLayout wrapping too soon

The JTextArea named txtaObservation is occupying five horizontal slots of its container's GridBagLayout. Its text should wrap by when it reaches the fifth slot, below the label named lblObservationLimit, however it is wrapping too soon, just about in the first slot. How do I make it wrap at the correct slot?
JDViewCustomer.java
package test2;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Objects;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JDViewCustomer extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private JTextArea txtaObservation;
private JPanel panelCustomerData;
private final CustomerData customerData;
private JLabel lblObservationLimit;
public JDViewCustomer(java.awt.Frame parent, boolean modal, CustomerData customerData) {
super(parent, modal);
this.customerData = Objects.requireNonNull(customerData);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
layoutCustomerDataSection();
addCustomerData();
initComponents();
}
public void layoutCustomerDataSection() {
panelCustomerData = new JPanel();
panelCustomerData.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelCustomerData.setBackground(Color.WHITE);
getContentPane().add(panelCustomerData);
GridBagLayout gbl_panelCustomerData = new GridBagLayout();
gbl_panelCustomerData.columnWidths = new int[]{58, 199, 38, 102, 27, 138, 0};
gbl_panelCustomerData.rowHeights = new int[]{0, 14, 0};
gbl_panelCustomerData.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelCustomerData.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelCustomerData.setLayout(gbl_panelCustomerData);
lblObservationLimit = new JLabel("Observation limit");
GridBagConstraints gbc_lblObservationLimit = new GridBagConstraints();
gbc_lblObservationLimit.insets = new Insets(0, 0, 5, 0);
gbc_lblObservationLimit.gridx = 5;
gbc_lblObservationLimit.gridy = 0;
panelCustomerData.add(lblObservationLimit, gbc_lblObservationLimit);
txtaObservation = new JTextArea("Observation text");
txtaObservation.setFont(new Font("Tahoma", Font.PLAIN, 11));
txtaObservation.setLineWrap(true);
txtaObservation.setWrapStyleWord(true);
GridBagConstraints gbc_txtaObservation = new GridBagConstraints();
gbc_txtaObservation.gridwidth = 5;
gbc_txtaObservation.anchor = GridBagConstraints.NORTHWEST;
gbc_txtaObservation.gridx = 1;
gbc_txtaObservation.gridy = 1;
panelCustomerData.add(txtaObservation, gbc_txtaObservation);
}
public void addCustomerData() {
txtaObservation.setText(customerData.getObservation());
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("View customer");
pack();
setLocationRelativeTo(getParent());
}
}
CustomerData.java
package test2;
public class CustomerData {
private final String observation;
public CustomerData(String observation) {
this.observation = observation;
}
public String getObservation() {
return observation;
}
}
Test2.java
package test2;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test2 {
private static void createAndShowGUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CustomerData customerData = new CustomerData("Testing a long observation text that should wrap only when reaching the observation limit.");
new JDViewCustomer(frame, true, customerData).setVisible(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Try this for JDViewCustomer.java -- comments are flagged with "// kwb". I didn't realize until just now that it was unofficially answered!
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Objects;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JDViewCustomer extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private JTextArea txtaObservation;
private JPanel panelCustomerData;
private final CustomerData customerData;
private JLabel lblObservationLimit;
public JDViewCustomer(java.awt.Frame parent, boolean modal, CustomerData customerData) {
super(parent, modal);
this.customerData = Objects.requireNonNull(customerData);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
layoutCustomerDataSection();
addCustomerData();
initComponents();
}
public void layoutCustomerDataSection() {
panelCustomerData = new JPanel();
panelCustomerData.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelCustomerData.setBackground(Color.WHITE);
getContentPane().add(panelCustomerData);
GridBagLayout gbl_panelCustomerData = new GridBagLayout();
gbl_panelCustomerData.columnWidths = new int[]{58, 199, 38, 102, 27, 138, 0};
gbl_panelCustomerData.rowHeights = new int[]{0, 14, 0};
gbl_panelCustomerData.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelCustomerData.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelCustomerData.setLayout(gbl_panelCustomerData);
lblObservationLimit = new JLabel("Observation limit");
GridBagConstraints gbc_lblObservationLimit = new GridBagConstraints();
gbc_lblObservationLimit.insets = new Insets(0, 0, 5, 0);
gbc_lblObservationLimit.gridx = 5;
gbc_lblObservationLimit.gridy = 0;
// kwb set gridheight to total number of rows
gbc_lblObservationLimit.gridheight = 2;
panelCustomerData.add(lblObservationLimit, gbc_lblObservationLimit);
txtaObservation = new JTextArea("Observation text");
// kwb just to help view issue
txtaObservation.setBorder(BorderFactory.createLineBorder(Color.blue));
txtaObservation.setFont(new Font("Tahoma", Font.PLAIN, 11));
txtaObservation.setLineWrap(true);
txtaObservation.setWrapStyleWord(true);
GridBagConstraints gbc_txtaObservation = new GridBagConstraints();
gbc_txtaObservation.gridwidth = 5;
gbc_txtaObservation.anchor = GridBagConstraints.NORTHWEST;
// kwb fill all available horizontal space
gbc_txtaObservation.fill = GridBagConstraints.HORIZONTAL;
// kwb change to start in column 0, adjust as necessary
gbc_txtaObservation.gridx = 0;
gbc_txtaObservation.gridy = 1;
panelCustomerData.add(txtaObservation, gbc_txtaObservation);
}
public void addCustomerData() {
txtaObservation.setText(customerData.getObservation());
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("View customer");
pack();
setLocationRelativeTo(getParent());
}
}

JButton can't be resolved inside actionListener

I'm trying to make a simple GUI calculator with Eclipse
The actionlistener is at the bottom, and eclipse says my ButtonAdd can't be resolved
the error is around lines 125-131, Any help is appreciated! :D
package main;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
public class GUIApp {
private JFrame frame;
public JTextField txtNumber_1;
public JTextField txtNumber;
public JTextField textField;
public JButton ButtonAdd;
public JButton ButtonSub;
public JButton ButtonMulti;
public JButton ButtonDiv;
public JButton btnRng;
String num1;
String num2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUIApp window = new GUIApp();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUIApp() {
initialize();
}
/**
* Initialize the contents of the frame.
* #return
*/
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
ButtonAdd = new JButton("Addition");
ButtonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
num1 = txtNumber_1.getText();
num2 = txtNumber.getText();
if(ButtonAdd.getModel().isPressed())
textField.setText(num1 + num2);
}
});
GridBagConstraints gbc_ButtonAdd = new GridBagConstraints();
gbc_ButtonAdd.insets = new Insets(0, 0, 5, 5);
gbc_ButtonAdd.gridx = 0;
gbc_ButtonAdd.gridy = 0;
frame.getContentPane().add(ButtonAdd, gbc_ButtonAdd);
ButtonSub = new JButton("Subtraction");
GridBagConstraints gbc_ButtonSub = new GridBagConstraints();
gbc_ButtonSub.insets = new Insets(0, 0, 5, 5);
gbc_ButtonSub.gridx = 0;
gbc_ButtonSub.gridy = 2;
frame.getContentPane().add(ButtonSub, gbc_ButtonSub);
txtNumber_1 = new JTextField();
txtNumber_1.setText("Number 1");
txtNumber_1.setToolTipText("insert a number");
GridBagConstraints gbc_txtNumber_1 = new GridBagConstraints();
gbc_txtNumber_1.insets = new Insets(0, 0, 5, 0);
gbc_txtNumber_1.fill = GridBagConstraints.HORIZONTAL;
gbc_txtNumber_1.gridx = 3;
gbc_txtNumber_1.gridy = 2;
frame.getContentPane().add(txtNumber_1, gbc_txtNumber_1);
txtNumber_1.setColumns(10);
ButtonMulti = new JButton("Multiplication");
GridBagConstraints gbc_ButtonMulti = new GridBagConstraints();
gbc_ButtonMulti.insets = new Insets(0, 0, 5, 5);
gbc_ButtonMulti.gridx = 0;
gbc_ButtonMulti.gridy = 4;
frame.getContentPane().add(ButtonMulti, gbc_ButtonMulti);
txtNumber = new JTextField();
txtNumber.setText("Number 2");
txtNumber.setToolTipText("insert other number");
GridBagConstraints gbc_txtNumber = new GridBagConstraints();
gbc_txtNumber.insets = new Insets(0, 0, 5, 0);
gbc_txtNumber.fill = GridBagConstraints.HORIZONTAL;
gbc_txtNumber.gridx = 3;
gbc_txtNumber.gridy = 5;
frame.getContentPane().add(txtNumber, gbc_txtNumber);
txtNumber.setColumns(10);
ButtonDiv = new JButton("Division");
GridBagConstraints gbc_ButtonDiv = new GridBagConstraints();
gbc_ButtonDiv.insets = new Insets(0, 0, 5, 5);
gbc_ButtonDiv.gridx = 0;
gbc_ButtonDiv.gridy = 6;
frame.getContentPane().add(ButtonDiv, gbc_ButtonDiv);
btnRng = new JButton("RNG");
GridBagConstraints gbc_btnRng = new GridBagConstraints();
gbc_btnRng.insets = new Insets(0, 0, 0, 5);
gbc_btnRng.gridx = 0;
gbc_btnRng.gridy = 8;
frame.getContentPane().add(btnRng, gbc_btnRng);
textField = new JTextField();
textField.setToolTipText("output");
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.gridx = 3;
gbc_textField.gridy = 8;
frame.getContentPane().add(textField, gbc_textField);
textField.setColumns(10);
}
public void actionPerformed(ActionEvent arg0) {
String num1;
String num2;
num1 = txtNumber_1.getText();
num2 = txtNumber.getText();
if(ButtonAdd.getModel().isPressed())
textField.setText(num1 + num2);
}
}
The GUI was made with WindowBuilder by the way
ButtonAdd is a local reference, meaning it can only be accessed inside the initialize method. A solution to this is to declare the ButtonAdd outside the method.
JButton ButtonAdd;
public void initialize() {
ButtonAdd = new JButton("Addition");
}
public void actionPerformed(ActionEvent arg0) {
// here we can now access ButtonAdd
}
Also a tip, by java's standard naming conventions you usually start variables and references with a lower case letter, so ButtonAdd -> buttonAdd
because it is not a member variable. make it one and it works
JButton ButtonAdd = new JButton("Addition"); is inside another method therefore it is not visible to your action listener

CardLayout appearing without asking for it

This is my SSCE (though in three seperate classes).
StartUp.java
public class Startup {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame gui = new MainFrame();
}
});
}
}
MainFrame.java
package gui;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class MainFrame {
private JFrame mainFrame;
private JMenuBar menuBar;
private JMenu menuRoboControl;
private JMenuItem menuItemStart;
private JMenuItem menuItemShutdown;
private JPanel cardPanel;
private final JPanel comListCard = new ComListCard();
public MainFrame() {
initComponents();
}
private void menuItemStartActionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) cardPanel.getLayout();
cardLayout.show(cardPanel, "selectPort");
}
private void menuItemShutdownActionPerformed(ActionEvent e) {
mainFrame.dispose();
System.exit(0);
}
private void initComponents() {
mainFrame = new JFrame();
menuBar = new JMenuBar();
menuRoboControl = new JMenu();
menuItemStart = new JMenuItem();
menuItemShutdown = new JMenuItem();
cardPanel = new JPanel();
//======== mainFrame ========
{
Container mainFrameContentPane = mainFrame.getContentPane();
mainFrameContentPane.setLayout(new BoxLayout(mainFrameContentPane, BoxLayout.X_AXIS));
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//======== menuBar ========
{
//======== menuRoboControl ========
{
menuRoboControl.setText("RoboControl");
//---- menuItemStart ----
menuItemStart.setText("Start Robot");
menuItemStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuItemStartActionPerformed(e);
}
});
menuRoboControl.add(menuItemStart);
//---- menuItemShutdown ----
menuItemShutdown.setText("Shutdown Robot");
menuItemShutdown.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuItemShutdownActionPerformed(e);
}
});
menuRoboControl.add(menuItemShutdown);
}
menuBar.add(menuRoboControl);
}
mainFrame.setJMenuBar(menuBar);
//======== cardPanel ========
{
cardPanel.setLayout(new CardLayout());
cardPanel.add(comListCard, "selectPort");
}
mainFrameContentPane.add(cardPanel);
mainFrame.setSize(835, 635);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
}
}
ComListCard.java
package gui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ComListCard extends JPanel {
private JTextArea portInfo;
private JScrollPane scrollPane1;
private JList<String> portList;
private JButton selectPort;
public ComListCard() {
initComponents();
}
public void initComponents() {
portInfo = new JTextArea();
scrollPane1 = new JScrollPane();
portList = new JList<>();
selectPort = new JButton();
//======== comListCard ========
{
this.setLayout(new GridBagLayout());
((GridBagLayout) this.getLayout()).columnWidths = new int[]{298, 214, 0, 0};
((GridBagLayout) this.getLayout()).rowHeights = new int[]{0, 0, 0, 0, 86, 220, 0, 0, 0};
((GridBagLayout) this.getLayout()).columnWeights = new double[]{0.0, 0.0, 1.0, 1.0E-4};
((GridBagLayout) this.getLayout()).rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0E-4};
//---- portInfo ----
portInfo.setText("Select the port connected to your XBee. If you do not know what port it is connected to, check your Device Manager.");
portInfo.setLineWrap(true);
portInfo.setWrapStyleWord(true);
portInfo.setOpaque(false);
portInfo.setEnabled(false);
portInfo.setEditable(false);
portInfo.setBorder(null);
this.add(portInfo, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//======== scrollPane1 ========
{
//---- portList ----
portList.setModel(new AbstractListModel<String>() {
String[] values = {
"1",
"2",
"3",
"4"
};
#Override
public int getSize() {
return values.length;
}
#Override
public String getElementAt(int i) {
return values[i];
}
});
scrollPane1.setViewportView(portList);
}
this.add(scrollPane1, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- selectPort ----
selectPort.setText("Select");
this.add(selectPort, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
}
}
}
Now some information on the problem. GUI works fine, purely about the CardLayout. As you can see I created a main window with a JPanel inside acting as the holder of the card. I created a card and have added it too to CardLayout. But it already appears from the start of the program while it should only appear after pressing the button (referring to the actionlistener where I put .show(..).
Any help appreciated. Not in a hurry either.
A CardLayout is designed to "hold" multiple cards (panels), but only one card will ever be displayed at a time. The key is that "one" of the panels is always displayed. So the CardLayout is functioning properly.
If you has an application that needs to dynamically display an panel on a frame then you must add the panel at run time. In this case the basic logic would be:
panel.add(...);
panel.revalidate();
panel.repaint();
With the above approach, space is not reserved on the frame for the panel when the frame is initially displayed (so you may also need to pack() the frame to make sure the panel is visible).
If you really want to see an empty space for your card panel when the frame is displayed, then you could simply create a panel with no components added to it and then add this panel to your CardLayout. Then when you invoke the show() method, you will swap in your panel with the components.

How to get CardLayout implemented properly with Eclipse WindowBuilder?

So using WindowBuilder (latest version of Ecliple, Kepler) I've created a frame as so:
But I'd like to switch between them with a button, which I've created on the panelWelcome.
I'm guessing I'd add an itemListener, then create a method that switches between the cards.
The problem is, I have no idea how to proceed after that. Here's the code that's automatically generated:
package client;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Test {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
JPanel panelWelcome = new JPanel();
frame.getContentPane().add(panelWelcome, "name_98933171901972");
GridBagLayout gbl_panelWelcome = new GridBagLayout();
gbl_panelWelcome.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_panelWelcome.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panelWelcome.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panelWelcome.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panelWelcome.setLayout(gbl_panelWelcome);
JLabel lblTitle = new JLabel("MEMEPlayer");
lblTitle.setFont(new Font("Segoe UI", Font.BOLD, 12));
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
gbc_lblTitle.gridx = 5;
gbc_lblTitle.gridy = 0;
panelWelcome.add(lblTitle, gbc_lblTitle);
JLabel lblNewLabel = new JLabel("Welcome! To get started, select a movie from the drop down menu");
lblNewLabel.setFont(new Font("Segoe UI", Font.PLAIN, 11));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 5;
gbc_lblNewLabel.gridy = 2;
panelWelcome.add(lblNewLabel, gbc_lblNewLabel);
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"The Avengers (2012)", "Monsters, Inc. (2001)", "Prometheus (2012)"}));
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.insets = new Insets(0, 0, 5, 0);
gbc_comboBox.gridx = 5;
gbc_comboBox.gridy = 4;
panelWelcome.add(comboBox, gbc_comboBox);
JButton btnNewButton = new JButton("Next >");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton.gridx = 5;
gbc_btnNewButton.gridy = 6;
btnNewButton.addItemListener((ItemListener) this);
panelWelcome.add(btnNewButton, gbc_btnNewButton);
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setIcon(new ImageIcon("C:\\temp\\Meme1\\largeVLC.png"));
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.gridx = 5;
gbc_lblNewLabel_1.gridy = 8;
panelWelcome.add(lblNewLabel_1, gbc_lblNewLabel_1);
JPanel panelVideo = new JPanel();
frame.getContentPane().add(panelVideo, "name_98968999152440");
}
}
Thanks for any help!
The problem I see you're facing is that you are setting the layout to the frame. This is a problem because it means that the frame can only have on visible component at a time. That component being one of the panels. So you can put a button. The button would have to be on the one of the panels, which may be hard to maintain, in terms of navigation.
So instead, have a main JPanel that has the CardLayout, and add your card panels to that main panel. Then you can add the main panel to the frame, along with buttons for navigation.
Another option is to have a menu bar with option to change the cards, then that way, you can keep the card layout on the frame, because navigation is controlled by the menu options.
See How to Use CardLayout if you're not really sure even how to use CardLayout, hand coding. You're going to need a reference to layout and call one of its navigation methods like show(), next(), or previous()
You may also find this post interesting. It used Netbeans, but maybe you'll pick something up

Why are my labels spaced out so far in the GridBagLayout?

Im new to GUI's in Java and having a hell of a time understanding this:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
public class Main extends JFrame {
private JPanel contentPane;
static JPanel panel;
static JScrollPane scrollPane;
static JButton btnStart;
private static String compTestArray[];
static Integer indexer = 0;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 739, 456);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnStart = new JButton("Start");
btnStart.setBounds(10, 379, 89, 23);
btnStart.addActionListener(new ButtonListener());
contentPane.add(btnStart);
panel = new JPanel();
panel.setBounds(10, 11, 513, 359);
contentPane.add(panel);
scrollPane = new JScrollPane(panel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
scrollPane.setBounds(10, 11, 633, 359);
contentPane.add(scrollPane);
compTestArray = new String[2];
compTestArray[0] = "172.16.98.3";
compTestArray[1] = "172.16.98.6";
}
static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
//String labelText = "Computer Name\tTest Name\tIteration\tPass\tFail\tCrashes\tStart\tStop";
//labelText = labelText.replaceAll("\t", " ");
listOfLabels.add(new JLabel("Computer"));
for(int ix = 0; ix < compTestArray.length; ix++){
// Clear panel
panel.removeAll();
//labelText = compTestArray[indexer] + "\tKPI_1_1_1_1\t" + ix + "/20\t1\t\t0\t\t0\t\t12:00\t12:30";
//labelText = labelText.replaceAll("\t", " ");
listOfLabels.add(new JLabel(compTestArray[indexer]));
System.out.println("indexer is " + indexer);
// Create constraints
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer+2; i++) {
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.weightx = 0;
labelConstraints.insets = new Insets(10, 10, 10, 10);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
// Repaint the GUI
scrollPane.validate();
} // Close for loop
// Disable Start button
btnStart.setEnabled(false);
} // Close public void actionPerformed(ActionEvent arg0)
} // Close static class ButtonListener implements ActionListener
}
Output:

Categories

Resources