I have designed a frame containing a few controls using the design view in Netbeans 6.9.1. Further, I have added an empty panel in which I am trying to toggle display of a couple of swing components on button click. The problem is that on button click, the panel displays nothing. The code is as follows:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JPanel txtPanel = new JPanel();
JPanel listPanel = new JPanel();
JTextField txtfield = new JTextField("ABCDEFGHIJ", 20);
txtPanel.add(txtfield);
JList<String> list = new JList<String>();
DefaultListModel<String> model = new DefaultListModel<String>();
for (int i = 0; i < userCommands.size(); i++){
model.addElement(userCommands.get(i));
}
list.setModel(model);
listPanel.add(list);
jPanel2.add(listPanel, "list");
jPanel2.add(txtPanel, "text");
//MainUI.getFrames()[0].add(jPanel2, BorderLayout.CENTER);
itemStateChanged("text");
}
Code for itemStateChanged is as follows:
public void itemStateChanged(String disp) {
CardLayout cl = (CardLayout)(jPanel2.getLayout());
cl.show(jPanel2, disp);
}
In the first piece of code, jPanel2 is dragged and dropped onto the frame containing other components, what i am trying to achieve here is that on button click, the jPanel2 should toggle between text field and list. But currently, the panel is not displaying anything on button click.
Before even considering if jPanel2 can switch between the different panels (the different cards), is jPanel2 on display at all anywhere? The only code I can see that displayes the jPanel2 is adding it to the MainUI but it is commented out?! So how do you know that the display inside jPanel2 isn't switching?
I did a quick example code for you .Have a look.You need to define the Card layout as global and try.
import javax.swing.AbstractAction;
public class TestPanel extends JPanel {
/**
* Create the panel.
*/
JPanel panel;
CardLayout cl = new CardLayout();
public TestPanel() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 155, 0, 0};
gridBagLayout.rowHeights = new int[]{94, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JButton btnNewButton = new JButton("New button");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 0;
add(btnNewButton, gbc_btnNewButton);
btnNewButton.setAction(new AbstractAction("New button") {
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel txtPanel = new JPanel();
JPanel listPanel = new JPanel();
JTextField txtfield = new JTextField("ABCDEFGHIJ", 20);
txtPanel.add(txtfield);
JList<String> list = new JList<String>();
DefaultListModel<String> model = new DefaultListModel<String>();
for (int i = 0; i < 3; i++){
model.addElement("Sanjaya");
}
list.setModel(model);
listPanel.add(list);
panel.add(listPanel, "list");
panel.add(txtPanel, "text");
//MainUI.getFrames()[0].add(jPanel2, BorderLayout.CENTER);
itemStateChanged("list");
}
});
JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
GridBagConstraints gbc_textArea = new GridBagConstraints();
gbc_textArea.insets = new Insets(0, 0, 5, 5);
gbc_textArea.fill = GridBagConstraints.BOTH;
gbc_textArea.gridx = 1;
gbc_textArea.gridy = 0;
add(textArea, gbc_textArea);
panel = new JPanel(cl);
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.insets = new Insets(0, 0, 5, 0);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 2;
gbc_panel.gridy = 0;
add(panel, gbc_panel);
}
public void itemStateChanged(String disp) {
cl.show(panel, disp);
}
}
Related
I have this JFrame named MainFrame and I'm trying to separate each panel into it's own class. I tried and failed with some errors.
Please see the code that I tried. What failed and what did I get wrong?
public class MainFrame extends JFrame {
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private StartScreenPlayerPanel startScreenPlayerPanel;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
System.out.println(screenSize);
frame.setMinimumSize(new Dimension(screenSize.width/2, screenSize.height/2));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
startScreenPlayerPanel = new StartScreenPlayerPanel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, (screenSize.width * 2 / 3), (screenSize.height * 2 / 3));
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{1200, 0};
gbl_contentPane.rowHeights = new int[]{74, 0, 446, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblTitle = new JLabel("The Coin Game",SwingConstants.CENTER);
lblTitle.setFont(new Font("Arial", Font.PLAIN, (int)screenSize.width/30));
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.gridwidth = 2;
gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
gbc_lblTitle.anchor = GridBagConstraints.NORTH;
gbc_lblTitle.fill = GridBagConstraints.HORIZONTAL;
gbc_lblTitle.gridx = 0;
gbc_lblTitle.gridy = 0;
contentPane.add(lblTitle, gbc_lblTitle);
JPanel StartScreenBtnPanel = new JPanel();
GridBagConstraints gbc_StartScreenBtnPanel = new GridBagConstraints();
gbc_StartScreenBtnPanel.gridwidth = 0;
gbc_StartScreenBtnPanel.insets = new Insets(0, 0, 5, 0);
gbc_StartScreenBtnPanel.fill = GridBagConstraints.BOTH;
gbc_StartScreenBtnPanel.gridx = 0;
gbc_StartScreenBtnPanel.gridy = 1;
contentPane.add(StartScreenBtnPanel, gbc_StartScreenBtnPanel);
StartScreenBtnPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnAddPlayer = new JButton("Add Player");
btnAddPlayer.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnAddPlayer);
JButton btnStartGame = new JButton("Start Game");
btnStartGame.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnStartGame);
The code I'm trying to separate to a different Class
// JPanel tblPanel = new JPanel();
// GridBagConstraints gbc_tblPanel = new GridBagConstraints();
// gbc_tblPanel.gridwidth = 2;
// gbc_tblPanel.insets = new Insets(0, 0, 5, 0);
// gbc_tblPanel.fill = GridBagConstraints.BOTH;
// gbc_tblPanel.gridx = 0;
// gbc_tblPanel.gridy = 2;
// contentPane.add(tblPanel, gbc_tblPanel);
// tblPanel.setLayout(new BorderLayout(0, 0));
// table = new JTable();
// tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
// table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 16));
// table.setModel(new DefaultTableModel(
// new Object[][] {
// },
// new String[] {
// "New Player", "Initial Points"
// }
// ) {
// Class[] columnTypes = new Class[] {
// String.class, Integer.class
// };
// public Class getColumnClass(int columnIndex) {
// return columnTypes[columnIndex];
// }
// });
// table.getColumnModel().getColumn(0).setResizable(false);
// table.getColumnModel().getColumn(0).setMinWidth(14);
// tblPanel.add(table, BorderLayout.CENTER);
What I tried
At the end of MainFrame Class
contentPane.add(startScreenPlayerPanel, startScreenPlayerPanel.getSSPPConstraints());
}
public StartScreenPlayerPanel getStartScreenPlayerPanel() {
return startScreenPlayerPanel;
}
New Class - StartScreenPlayerPanel
public class StartScreenPlayerPanel extends JFrame {
MainFrame mainframe;
private JTable table;
private GridBagConstraints gbc_tblPanel = new GridBagConstraints();
public StartScreenPlayerPanel() {
JPanel tblPanel = new JPanel();
gbc_tblPanel.gridwidth = 2;
gbc_tblPanel.insets = new Insets(0, 0, 5, 0);
gbc_tblPanel.fill = GridBagConstraints.BOTH;
gbc_tblPanel.gridx = 0;
gbc_tblPanel.gridy = 2;
tblPanel.setLayout(new BorderLayout(0, 0));
table = new JTable();
tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 16));
table.setModel(new DefaultTableModel(new Object[][] {}, new String[] { "New Player", "Initial Points" }) {
Class[] columnTypes = new Class[] { String.class, Integer.class };
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
});
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(0).setMinWidth(14);
tblPanel.add(table, BorderLayout.CENTER);
}
public GridBagConstraints getSSPPConstraints(){
return gbc_tblPanel;
}
}
I'm trying to seperate each panel to it's own class
public class StartScreenPlayerPanel extends JFrame {
Ok, so why are you extending JFrame?
If you want to add a panel to the main frame then you extend JPanel:
public class StartScreenPlayerPanel extends JPanel {
Now because your class "is a" JPanel, you just set the layout manager of the panel and add components to it.
public StartScreenPlayerPanel()
{
setLayout(new BorderLayout());
table = new JTable();
table.setModel( ... );
add(table.getTableHeader(), BorderLayout.NORTH);
add(table, BorderLayout.CENTER);
}
There is no need for the getSSPPConstraints() method in this class. The "StartScreenPlayerPanel" doesn't know or care how the panel is used. It only worries about the layout of the components in its own class.
The result is a JPanel with a JTable added to the JPanel.
Note: typically when using a JTable you would use:
//add(table.getTableHeader(), BorderLayout.NORTH);
//add(table, BorderLayout.CENTER);
add(new JScrollPane(table), BorderLayout.CENTER);
The scrollpane will automatically add the table header to itself.
Now in your main class you add the panel to the content pane:
//contentPane.add(startScreenPlayerPanel, startScreenPlayerPanel.getSSPPConstraints());
GridBagConstraints gbc_playerPanel = new GridBagConstraints();
gbc_playerPanel.gridwidth = 2;
gbc_playerPanel.insets = new Insets(0, 0, 5, 0);
gbc_playerPanel.fill = GridBagConstraints.BOTH;
gbc_playerPanel.gridx = 0;
gbc_playerPanel.gridy = 2;
contentPane.add(startScreenPlayeerPanel, gbc_playerPanel).
That is the constraints are the property of the class that adds the panel to the content panel.
The below code creates the following GUI.
But I would like to have TextFields "A" and "C" completely fill their respective rows (so that their right corners are aligned with the right edge of the JComboBox. Help would be much appreciated!
Here's the code:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
Dimension size = new Dimension( 310, 210 );
frame.setSize(size);
frame.setPreferredSize(size);
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JTextField tf3 = new JTextField();
JLabel label1 = new JLabel( "A");
JLabel label2 = new JLabel( "B");
JLabel label3 = new JLabel( "C");
String[] opts = {"1","2","3"};
JComboBox dropdown = new JComboBox(opts);
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup().
addComponent(label1).addComponent(label2).
addComponent(label3));
hGroup.addGroup(layout.createParallelGroup().
addComponent(tf1).addComponent(tf2).
addComponent(tf3));
hGroup.addGroup(layout.createParallelGroup().addComponent(dropdown));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label1).addComponent(tf1));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label2).addComponent(tf2).addComponent(dropdown));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label3).addComponent(tf3));
layout.setVerticalGroup(vGroup);
frame.add( panel, BorderLayout.NORTH );
frame.setVisible(true);
I think the best for this would be to use GridBagLayout, it is al little bit hard to use, but if you read some tutorials you'll find that it is the perfect solution for you.
GridBagLayout have weight in x and y, fill in x and y, and it is like a table.
You need to specify table with 2 columns, and three rows.
then each element need to be positioned in this table row and column, but the A and C should have gridtWidth set to 2 columns. And in the middle row you put jtextdield in one column, and jcombobox in the second.
Here you have sample program that do this:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JComboBox;
public class Example {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Example window = new Example();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Example() {
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[] {500, 500};
gridBagLayout.rowHeights = new int[] {50, 50, 50};
gridBagLayout.columnWeights = new double[]{1.0, 1.0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0};
frame.getContentPane().setLayout(gridBagLayout);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.weightx = 1.0;
gbc_textField.gridwidth = 2;
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 0;
gbc_textField.gridy = 0;
frame.getContentPane().add(textField, gbc_textField);
textField.setColumns(10);
textField_1 = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.weightx = 1.0;
gbc_textField_1.insets = new Insets(0, 0, 5, 5);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 0;
gbc_textField_1.gridy = 1;
frame.getContentPane().add(textField_1, gbc_textField_1);
textField_1.setColumns(10);
JComboBox comboBox = new JComboBox();
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.weightx = 1.0;
gbc_comboBox.insets = new Insets(0, 0, 5, 0);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 1;
gbc_comboBox.gridy = 1;
frame.getContentPane().add(comboBox, gbc_comboBox);
textField_2 = new JTextField();
GridBagConstraints gbc_textField_2 = new GridBagConstraints();
gbc_textField_2.weightx = 1.0;
gbc_textField_2.gridwidth = 2;
gbc_textField_2.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_2.gridx = 0;
gbc_textField_2.gridy = 2;
frame.getContentPane().add(textField_2, gbc_textField_2);
textField_2.setColumns(10);
}
}
It is hard to write UI by hand if you are not very familiar. Better idea is to use some UI Design tools. For example WindowBuilder in Eclipse. It can read and show your Frames and allow you to add button by just dragging it to the right place in the frame, it is a lot easier and faster. If you click in the added element you will automatically get created an action listener and you are ready to write the code for the action. I recommend this way of building UIs:)
Here's what I want the end result to look like...
I am trying to use a GridBagLayout for this but not sure if its the right choice because it's coming out all over the place. I know I shouldn't write all my code in a single constructor but here's what I have so far...
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.Font;
import java.awt.event.*;
import static java.lang.Math.*;
public class HomeStylePizza extends JFrame{
private static final int WIDTH = 500;
private static final int HEIGHT = 400;
//GUI components
private JLabel lblEachTopping, lblPizzaSize, lblPizzaType, lblWelcome, lblYourOrder;
private JButton btnProcessSelection;
private JCheckBox cbPepproni, cbSausage, cbMushrooms, cbPineapple, cbOnion, cbBellPepper;
private JRadioButton rbSmall, rbMedium, rbLarge, rbThinCrust, rbMediumCrust, rbPan;
private ButtonGroup grp1, grp2;
private JTextArea textArea;
private CalculateButtonHandler cbHandler;
public HomeStylePizza()
{
//Create new labels
lblEachTopping = new JLabel("Each Topping: $1.50");
lblPizzaSize = new JLabel("Pizza Size");
lblPizzaType = new JLabel("Pizza Type");
lblWelcome = new JLabel("Welcome to Home Style Pizza Shop");
lblYourOrder = new JLabel("Your order:");
//Create new buttons
btnProcessSelection = new JButton("Process Selection");
cbHandler = new CalculateButtonHandler();
btnProcessSelection.addActionListener(cbHandler);
//Create new JCheckBoxes
cbPepproni = new JCheckBox("Pepproni");
cbSausage = new JCheckBox("Sausage");
cbMushrooms = new JCheckBox("Mushrooms");
cbPineapple = new JCheckBox("Pineapple");
cbOnion = new JCheckBox("Onion");
cbBellPepper = new JCheckBox("Bell Pepper");
//Create radio buttons
rbSmall = new JRadioButton("Small: $6.50");
rbMedium = new JRadioButton("Medium: $8.50");
rbLarge = new JRadioButton("Large: $10.00");
rbThinCrust = new JRadioButton("Thin Crust");
rbMediumCrust = new JRadioButton("Medium Crust");
rbPan = new JRadioButton("Pan");
//Create new TextArea
textArea = new JTextArea(6, 10);
//Set title
setTitle("Pizza Shop");
//Create new font layout
Font font = new Font("New Times Roman", Font.BOLD, 18);
//get the container
Container pane = getContentPane();
JPanel thePanel = new JPanel();
thePanel.setLayout(new GridBagLayout());
//set the layout
pane.setLayout(new GridBagLayout());
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.gridwidth = 1;
gridConstraints.gridheight = 1;
gridConstraints.weightx = 50;
gridConstraints.weighty = 100;
gridConstraints.insets = new Insets(5,5,5,5);
gridConstraints.anchor = GridBagConstraints.CENTER;
gridConstraints.fill = GridBagConstraints.BOTH;
//Place components in the pane
thePanel.add(lblWelcome, gridConstraints);
gridConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
gridConstraints.gridwidth = 20;
gridConstraints.gridx = 15;
lblWelcome.setFont(new Font("New Times Roman", Font.BOLD, 18));
lblWelcome.setForeground(Color.RED);
//Create new vertical box and place a titled border around it
Box optionBox1 = Box.createVerticalBox();
optionBox1.setBorder(BorderFactory.createTitledBorder(null, "Toppings", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//add components to optionBox1
optionBox1.add(lblEachTopping);
lblEachTopping.setForeground(Color.RED);
optionBox1.add(cbPepproni);
optionBox1.add(cbSausage);
optionBox1.add(cbMushrooms);
optionBox1.add(cbPineapple);
optionBox1.add(cbOnion);
optionBox1.add(cbBellPepper);
//add optionBox1 to WEST quadrant
thePanel.add(optionBox1, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LINE_START;
gridConstraints.gridwidth = 1;
gridConstraints.gridx = 1;
gridConstraints.gridy = 10;
//Create new vertical box and place a titled border around it
Box optionBox2 = Box.createVerticalBox();
optionBox2.setBorder(BorderFactory.createTitledBorder(null, "Pizza Size", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//Create new ButtonGroup
grp1 = new ButtonGroup();
//add components to optionBox2 and grp1
grp1.add(rbSmall);
grp1.add(rbMedium);
grp1.add(rbLarge);
optionBox2.add(rbSmall);
optionBox2.add(rbMedium);
optionBox2.add(rbLarge);
//add optionBox2 to CENTER
thePanel.add(optionBox2, gridConstraints);
gridConstraints.anchor = GridBagConstraints.CENTER;
gridConstraints.gridx = 3;
gridConstraints.gridy = 10;
Box btnBox = Box.createHorizontalBox();
btnBox.setBorder(BorderFactory.createEmptyBorder());
btnBox.add(btnProcessSelection);
thePanel.add(btnBox);
gridConstraints.anchor = GridBagConstraints.LAST_LINE_END;
gridConstraints.gridwidth = 5;
gridConstraints.gridx = 3;
gridConstraints.gridy = 12;
//Create new vertical box and place a titled border around it
Box optionBox3 = Box.createVerticalBox();
optionBox3.setBorder(BorderFactory.createTitledBorder(null, "Pizza Type", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//Create new ButtonGroup
grp2 = new ButtonGroup();
//add components to optionBox2 and grp1
grp2.add(rbThinCrust);
grp2.add(rbMediumCrust);
grp2.add(rbPan);
optionBox3.add(rbThinCrust);
optionBox3.add(rbMediumCrust);
optionBox3.add(rbPan);
//add optionBox3 to EAST
thePanel.add(optionBox3, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LINE_END;
gridConstraints.gridwidth = 1;
gridConstraints.gridx = 5;
gridConstraints.gridy = 10;
//Create box for lblYourOrder and textArea and
//add them to pane in SOUTH quadrant
Box orderBox = Box.createVerticalBox();
orderBox.setBorder(null);
orderBox.add(lblYourOrder);
orderBox.add(textArea);
thePanel.add(orderBox, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LAST_LINE_START;
gridConstraints.gridwidth = 30;
gridConstraints.gridx = 1;
gridConstraints.gridy = 13;
pane.add(thePanel);
//set window size and display it
setSize(WIDTH, HEIGHT);
setVisible(true);
//Center frame
this.setLocationRelativeTo(null);
this.pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}//End of constructor
public static void main(String[] args)
{
HomeStylePizza menuTest = new HomeStylePizza();
}//End of main
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
}//End of class
Its a bit ugly and you can ignore most of my comments I've been changing things around trying to fix it. I was using a different layout.
Edited: I went ahead and created the Pizza Shop GUI.
I used a combination of BorderLayouts and GridBagLayouts.
I grouped together the code to make it easier to follow. Grouping the code does not mean putting all of the JCheckBox initializations together. Grouping the code means that all of the elements that make up a JPanel are there, right next to each other. This way, you don't have to jump all over the code looking for the lines that define the JRadioButton rbMedium.
I used a separate GridBagConstraints for each Swing component to make it easier for me to debug the GUI.
I've left the action listener for you to code.
Here's the GUI code:
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
public class HomeStylePizza implements Runnable {
private static final Insets bottomInsets = new Insets(10, 10, 10, 10);
private static final Insets normalInsets = new Insets(10, 10, 0, 10);
// GUI components
private JCheckBox cbPepproni, cbSausage, cbMushrooms, cbPineapple, cbOnion,
cbBellPepper;
private JRadioButton rbSmall, rbMedium, rbLarge, rbThinCrust,
rbMediumCrust, rbPan;
private JTextArea textArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(new HomeStylePizza());
} // End of main
#Override
public void run() {
JFrame frame = new JFrame("Pizza Shop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
int gridy = 0;
addComponent(mainPanel, createTitlePanel(), 0, gridy++, 2, 1,
normalInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
addComponent(mainPanel, createToppingPanel(), 0, gridy, 1, 1,
normalInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new BorderLayout());
eastPanel.add(createSizePanel(), BorderLayout.WEST);
eastPanel.add(new JLabel(" "), BorderLayout.CENTER);
eastPanel.add(createTypePanel(), BorderLayout.EAST);
eastPanel.add(createButtonPanel(), BorderLayout.SOUTH);
addComponent(mainPanel, eastPanel, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
addComponent(mainPanel, createTextAreaPanel(), 0, gridy++, 2, 1,
bottomInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel();
JLabel lblWelcome = new JLabel("Welcome to Home Style Pizza Shop");
Font titleFont = lblWelcome.getFont().deriveFont(20F);
lblWelcome.setFont(titleFont);
lblWelcome.setForeground(Color.RED);
panel.add(lblWelcome);
return panel;
}
private JPanel createToppingPanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblEachTopping = new JLabel("Each Topping: $1.50");
lblEachTopping.setForeground(Color.RED);
panel.add(lblEachTopping);
cbPepproni = new JCheckBox("Pepperoni");
cbSausage = new JCheckBox("Sausage");
cbMushrooms = new JCheckBox("Mushrooms");
cbPineapple = new JCheckBox("Pineapple");
cbOnion = new JCheckBox("Onion");
cbBellPepper = new JCheckBox("Bell Pepper");
// add components to optionBox1
panel.add(cbPepproni);
panel.add(cbSausage);
panel.add(cbMushrooms);
panel.add(cbPineapple);
panel.add(cbOnion);
panel.add(cbBellPepper);
return panel;
}
private JPanel createSizePanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblPizzaSize = new JLabel("Pizza Size");
lblPizzaSize.setForeground(Color.RED);
panel.add(lblPizzaSize);
rbSmall = new JRadioButton("Small: $6.50");
rbMedium = new JRadioButton("Medium: $8.50");
rbLarge = new JRadioButton("Large: $10.00");
// Create new ButtonGroup
ButtonGroup group = new ButtonGroup();
group.add(rbSmall);
group.add(rbMedium);
group.add(rbLarge);
panel.add(rbSmall);
panel.add(rbMedium);
panel.add(rbLarge);
return panel;
}
private JPanel createTypePanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblPizzaType = new JLabel("Pizza Type");
lblPizzaType.setForeground(Color.RED);
panel.add(lblPizzaType);
rbThinCrust = new JRadioButton("Thin Crust");
rbMediumCrust = new JRadioButton("Medium Crust");
rbPan = new JRadioButton("Pan");
// Create new ButtonGroup
ButtonGroup group = new ButtonGroup();
// add components to optionBox2 and grp1
group.add(rbThinCrust);
group.add(rbMediumCrust);
group.add(rbPan);
panel.add(rbThinCrust);
panel.add(rbMediumCrust);
panel.add(rbPan);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
JButton btnProcessSelection = new JButton("Process Selection");
btnProcessSelection.addActionListener(new CalculateButtonHandler());
panel.add(btnProcessSelection);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JLabel lblYourOrder = new JLabel("Your order:");
panel.add(lblYourOrder, BorderLayout.NORTH);
textArea = new JTextArea(6, 12);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
private class CalculateButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
} // End of HomeStylePizza class
Use GridBagLayout, or use netbeans it will make it easy for you, other option use GridLayout(2,1)
in it 2 panel
panel 1 will have grid layout of 1,2 in it you first list and other pnael has grid layout of 2,1 first row is your second list and the second row will be the button finally put the order info in the second row of your base layout.
Okay, so I have made a GUI with some input boxes and a combo box. I am wondering how I would go about having a listener know when the button is pressed then relay all the information in the imput boxes and combo box into different parts of the script...
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class dogedice extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JComboBox combo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dogedice frame = new dogedice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public dogedice() {
setTitle("DogeDice Bot");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
//Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
JLabel userTag = new JLabel("Username:");
GridBagConstraints gbc_userTag = new GridBagConstraints();
gbc_userTag.insets = new Insets(0, 0, 0, 5);
gbc_userTag.anchor = GridBagConstraints.EAST;
gbc_userTag.gridx = 0;//Here are your x + y coords
gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
panel.add(userTag, gbc_userTag);
//Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
textField = new JTextField();
GridBagConstraints gbc_Username = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel startTag = new JLabel("Starting Bid:");
GridBagConstraints gbc_startTag = new GridBagConstraints();
gbc_startTag.insets = new Insets(0, 0, 0, 5);
gbc_startTag.anchor = GridBagConstraints.EAST;
gbc_startTag.gridx = 0;
gbc_startTag.gridy = 2;
panel.add(startTag, gbc_startTag);
textField = new JTextField();
GridBagConstraints gbc_StartBid = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 2;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel multTag = new JLabel("Multiplier:");
GridBagConstraints gbc_multTag = new GridBagConstraints();
gbc_multTag.insets = new Insets(0, 0, 0, 5);
gbc_multTag.anchor = GridBagConstraints.EAST;
gbc_multTag.gridx = 0;
gbc_multTag.gridy = 3;
panel.add(multTag, gbc_multTag);
textField = new JTextField();
GridBagConstraints gbc_Multiplier = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel minTag = new JLabel("Min Remaining:");
GridBagConstraints gbc_minTag = new GridBagConstraints();
gbc_minTag.insets = new Insets(0, 0, 0, 5);
gbc_minTag.anchor = GridBagConstraints.EAST;
gbc_minTag.gridx = 0;
gbc_minTag.gridy = 4;
panel.add(minTag, gbc_minTag);
textField = new JTextField();
GridBagConstraints gbc_MinRemaining = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 4;
panel.add(textField, gbc_textField);
textField.setColumns(10);
textField = new JTextField();
GridBagConstraints gbc_Password = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel passTag = new JLabel("Password:");
GridBagConstraints gbc_passTag = new GridBagConstraints();
gbc_passTag.insets = new Insets(0, 0, 0, 5);
gbc_passTag.anchor = GridBagConstraints.EAST;
gbc_passTag.gridx = 0;
gbc_passTag.gridy = 1;
panel.add(passTag, gbc_passTag);
textField = new JTextField();
GridBagConstraints gbc_Odds = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 5;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel oddsTag = new JLabel("Odds %:");
GridBagConstraints gbc_oddsTag = new GridBagConstraints();
gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
gbc_oddsTag.anchor = GridBagConstraints.EAST;
gbc_oddsTag.gridx = 0;
gbc_oddsTag.gridy = 5;
panel.add(oddsTag, gbc_oddsTag);
textField = new JTextField();
GridBagConstraints gbc_ComboBox = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 6;
panel.add(textField, gbc_textField);
textField.setColumns(10);
//This is the Combo Box
combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
combo.addActionListener(this);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.fill = GridBagConstraints.HORIZONTAL;
gbc_list.gridx = 1;
gbc_list.gridy = 7;
panel.add(combo, gbc_list);
JLabel maxTag = new JLabel("MaxBet:");
GridBagConstraints gbc_maxTag = new GridBagConstraints();
gbc_maxTag.insets = new Insets(0, 0, 0, 5);
gbc_maxTag.anchor = GridBagConstraints.EAST;
gbc_maxTag.gridx = 0;
gbc_maxTag.gridy = 6;
panel.add(maxTag, gbc_maxTag);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
JButton btnConfirm = new JButton("Turn Up");
panel_1.add(btnConfirm);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea("Current Balance");
textArea.setColumns(1);
scrollPane.setViewportView(textArea);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textAreal = new JTextArea("Input bot information here...");
textArea.setColumns(20);
scrollPane.setViewportView(textArea);
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == combo) {
System.out.println(combo.getSelectedIndex()+1);
}
}
}
It's quite straightforward to add an ActionListener to a JButton.
// ...
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(this);
panel_1.add(btnConfirm);
// ...
Because you'll want to know when the button is triggering the callback, like so:
private JButton btnConfirm;
This way, you'll be able to tell when it's that button that triggered the actionListener() method:
if (event.getSource() == btnConfirm) {
// Handle "Turn Up" button press here
}
Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
Essentially you need to register an ActionListener with your button...
There are a number of ways you might be able to achieve this...
You Could
Use the more traditional, purpose class...
public class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
if ("Turn Up".evt.getActionCommand()) {
// Handle Turn Up...
}
}
}
In this context, you'll be required to provide a reference to the component you want to modify so that the ActionHandler can interact with it, personally, this is best done via an interface, but that's just me...
public class ActionHandler implements ActionListener {
private dogedice dice;
public ActionHandler(dogedice dice) {
this.dice = dice;
}
public void actionPerformed(ActionEvent evt) {
//...
}
}
The benefit of this is you can plug an play the action handler, changing what the action does depending on your needs. If you use an interface instead of an implementation reference, you further decouple the action from the program
You Could
Use use an anonymous class
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// handle turn up action...
}
});
The benefit to this is, you don't end up with "another" class, the ActionListener can reference all the internal fields of the parent class and, because you've attached it directly, you can assume that the only thing that is going to generate the ActionEvent is the btnConfirm button.
The downside is you lose the flexibility to change how the action is handled without physically modifying the code
You Could
Take advantage of the Actions API, this is a little like the first option, in that you (should normally) create another class specifically designed to handle the "Turn Up" event, but these are self contained entities. That is, they carry all the information required to configure the UI element and perform the required action when triggered.
This is really good where the action may be repeated in the UI via menus, buttons or key strokes
I have a question regarding how to align my components on my GUI.
Referring to the screen capture above, I want the checkboxes to be aligned with each other, but here I'm getting that one checkbox (LC Proxy) which is out of line, due to there being an additional combo box on the same line.
Can anyone suggest the necessary changes I should make to achieve what I want? (Other suggestions on how to improve the code/display are also welcome!)
(P/S Sorry if the title is misleading; not sure how else I can name it)
Here's the code for my GUI:
/**
* Builds the elements for the GUI
*/
private void build() {
// define properties
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(100, 100);
this.setSize(360, 250);
this.setResizable(false);
// build elements
movFileField = new JTextField(30);
movFileField.setEditable(false);
JLabel textFieldLabel = new JLabel("MOV file: ");
textFieldLabel.setLabelFor(movFileField);
JPanel filenamePane = new JPanel();
filenamePane.setLayout(new FlowLayout());
filenamePane.add(textFieldLabel);
filenamePane.add(movFileField);
JCheckBox checkIPV = new JCheckBox("IPV Proxy");
checkIPV.setSelected(configMap.get(EpoxyConfigField.IPV_PROXY.name()).isEnabled());
toggleMap.put(EpoxyConfigField.IPV_PROXY, checkIPV);
flickComps.add(checkIPV);
JCheckBox checkITX = new JCheckBox("ITX Proxy");
checkITX.setSelected(configMap.get(EpoxyConfigField.ITX_PROXY.name()).isEnabled());
toggleMap.put(EpoxyConfigField.ITX_PROXY, checkITX);
flickComps.add(checkITX);
JCheckBox checkLC = new JCheckBox("LC Proxy");
checkLC.setSelected(configMap.get(EpoxyConfigField.LC_PROXY.name()).isEnabled());
toggleMap.put(EpoxyConfigField.LC_PROXY, checkLC);
flickComps.add(checkLC);
JComboBox<String> comboLCProfile = new JComboBox<String>("A;C;D;Dxd;E".split(";"));
JCheckBox checkArchive = new JCheckBox("Archive Asset");
checkArchive.setSelected(configMap.get(EpoxyConfigField.ARCHIVE.name()).isEnabled());
toggleMap.put(EpoxyConfigField.ARCHIVE, checkArchive);
flickComps.add(checkArchive);
JPanel checkboxPane = new JPanel();
checkboxPane.setLayout(new BoxLayout(checkboxPane, BoxLayout.PAGE_AXIS));
checkboxPane.add(checkIPV);
checkboxPane.add(checkITX);
// This is the part I'm having problems with
JPanel lcproxyPane = new JPanel();
lcproxyPane.add(checkLC);
lcproxyPane.add(comboLCProfile);
checkboxPane.add(lcproxyPane);
checkboxPane.add(checkArchive);
checkboxPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JButton processButton = new JButton("Process");
processButton.setActionCommand(COMMAND_PROCESS);
processButton.addActionListener(this);
flickComps.add(processButton);
JButton selectButton = new JButton("Select");
selectButton.setActionCommand(COMMAND_SELECT);
selectButton.addActionListener(this);
flickComps.add(selectButton);
statusField = new JTextArea(10,20);
statusField.setEditable(false);
statusField.setLineWrap(true);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(Box.createRigidArea(new Dimension(50, 0)));
buttonPane.add(processButton);
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(selectButton);
buttonPane.add(Box.createRigidArea(new Dimension(50, 0)));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
JPanel bottomPane = new JPanel();
bottomPane.setLayout(new BoxLayout(bottomPane, BoxLayout.PAGE_AXIS));
bottomPane.add(buttonPane);
bottomPane.add(new JScrollPane(statusField));
Container contentPane = this.getContentPane();
contentPane.add(filenamePane, BorderLayout.PAGE_START);
contentPane.add(checkboxPane, BorderLayout.CENTER);
contentPane.add(bottomPane, BorderLayout.PAGE_END);
this.pack();
}
The reason why you cannot align your components is because you used a layout which makes very difficult to align those components.
I suggest you to use GridBagLayout rather than FlowLayout.
Example:
JPanel checkboxPane = new JPanel();
GridBagLayout gbl_checkboxPane = new GridBagLayout();
gbl_checkboxPane.columnWidths = new int[]{430, 0, 0};
gbl_checkboxPane.rowHeights = new int[]{27, 27, 27, 27};
gbl_checkboxPane.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
gbl_checkboxPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
checkboxPane.setLayout(gbl_checkboxPane);
JCheckBox checkIPV = new JCheckBox("IPV Proxy");
GridBagConstraints gbc_checkIPV = new GridBagConstraints();
gbc_checkIPV.anchor = GridBagConstraints.WEST;
gbc_checkIPV.fill = GridBagConstraints.VERTICAL;
gbc_checkIPV.insets = new Insets(0, 0, 5, 5);
gbc_checkIPV.gridx = 0;
gbc_checkIPV.gridy = 0;
checkboxPane.add(checkIPV, gbc_checkIPV);