Display using JPanels/JFrames? - java

I have code done, but still have not managed to get what I am working for.
My current code shows this:
with this code:
/*
*/
package reader;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
//import java.lang.Process;
/**
*/
class readerGUI extends JFrame
{
JMenuBar menuBar;
JMenu menu1, menu2, menu3, menu4;
JMenuItem menuItem, menuItem1, menuItem2, menuItem3, menuItem4;
ImageIcon logo;
JLabel loguin1, loguin2, title;
JTextArea readerArea;
JPanel rightSide, leftSide, bottomSide, middleSide;
String text;
JButton importBook, removeBook, listBook, searchBook;
JTextField searchField;
readerGUI()
{
super("Text \n");
String cad = "logo.png";
//setBackground(Color.blue);
setLayout(new FlowLayout());
menuBar = new JMenuBar();
title = new JLabel(" Text ");
add(title);
menu1 = new JMenu("Link");
menuItem = new JMenuItem("Option");
menu2 = new JMenu("Link");
menuItem1 = new JMenuItem("Option In");
menuItem2 = new JMenuItem("Option Out");
menu3 = new JMenu("Link");
menuItem3 = new JMenuItem("Option");
menuBar.add(menu1);
menuBar.add(menu2);
menuBar.add(menu3);
menu1.add(menuItem);
menu2.add(menuItem1);
menu2.add(menuItem2);
menu3.add(menuItem3);
add(menuBar);
logo = new ImageIcon(cad);//create icon
loguin1 = new JLabel(logo);//create label
loguin2 = new JLabel(logo);//create label
//loguin.setBounds(150,30,100,100);//where?
add(loguin1); //add
add(loguin2);
rightSide = new JPanel(); //PANEL for buttons
rightSide.add(new JLabel("Text:"));
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement("Text1");
model.addElement("Text2");
model.addElement("Text3");
JComboBox comboBox = new JComboBox(model);
rightSide.add(comboBox);
searchField = new JTextField("", 10);
rightSide.add(searchField);
searchBook = new JButton("Search");
rightSide.add(searchBook);
add(rightSide);
text = "\n\t\t LORE IPSUM \n\n"
+ "commodo nisi. In hac habitasse platea dictumst.\n";
middleSide = new JPanel(); //PANEL for buttons
add(middleSide);
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setBackground(sas, Color.RED);
StyledDocument doc;
/* --------- SIDE Menu Panel for Options ----------*/
title = new JLabel("Options ");
add(title);
leftSide = new JPanel(); //PANEL for buttons
importBook = new JButton("Button1");
leftSide.add(importBook);
removeBook = new JButton("Button2");
leftSide.add(removeBook);
add(leftSide);
JPanel main = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel child = new JPanel();
child.add(new JLabel("Options \n"));
//main.add(child);
main.add(leftSide);
add(main);
ActionEventHandler manejador = new ActionEventHandler();
menuItem.addActionListener(manejador);
}
private class ActionEventHandler implements ActionListener
{
#Override
public void actionPerformed( ActionEvent evento)
{
if (evento.getSource() == menuItem)
System.exit(0);
}
}
}
And would like my code to display something along these lines:
I know im not that far from obtaining it, but I get confused with JPanels and JFrames.. help?

Generally speaking, FlowLayout probably isn't the best choice of layout manager in this case.
You're off to a good start by separating each area into separate components, but you should be focusing on their layout requirements as well.
To start with, I see the base layout as a BorderLayout. This will allow you to place the "title" in the BorderLayout.NORTH position, the "menu" in the BorderLayout.WEST position and the content into the BorderLayout.CENTER position
For the title, I see the use of GridBagLayout, as this will allow you to give the "Title" more weight (space) then the other components.
The menu is a little more complex, you might be able to do this with a GridBagLayout or, by separating the "Menu Options" from the buttons (in separate containers), use a BorderLayout as the base (placing "Menu Options" in the BorderLayout.NORTH and the buttons in the BorderLayout.CENTER position) and using something like a GridLayout for the buttons, for example...
For the "main content", you could use either a GridLayout or GridBagLayout depending on your needs
Take a look through Laying Out Components Within a Container for more ideas...

Related

JButton not showing up in scroll pane

I'm trying to setup a basic GUI Library that will import a list of books and display each book as a JButton within a scroll pane. But, before getting there I'm just trying to orient the panels first and adding a test button to make sure the basics are working before moving on to the details.
I've tried moving code around to add panels in different orders to see if that was an issue but keep getting the same result. I'm completely new to this, so my understanding of it is very limited.
public class LibraryPanel extends JPanel{
private Library library;
private JPanel bookButtons, importBooks;
JScrollPane bookList;
JTextField importField;
JButton load;
public LibraryPanel() {
setPreferredSize(new Dimension(200,500));
Library library = new Library();
setLayout(new BorderLayout());
this.setBorder(BorderFactory.createTitledBorder("Library"));
// Import Books Panel
importBooks = new JPanel();
importBooks.setLayout(new BoxLayout(importBooks,BoxLayout.X_AXIS));
importBooks.setBorder(BorderFactory.createTitledBorder("Import Books"));
importField = new JTextField(15);
importBooks.add(importField);
load = new JButton("Load");
importBooks.add(load);
this.add(importBooks,BorderLayout.SOUTH);
load.addActionListener(new loadButtonListener());
// Book List buttons
JPanel bookButtons = new JPanel();
bookButtons.setLayout(new BoxLayout(bookButtons,BoxLayout.Y_AXIS));
JButton testButton = new JButton("TEST Button");
bookButtons.add(testButton);
//for(int i = 0; i<library.getBooks().size(); i++) {
// BookButton button = new BookButton(library.getBook(i));
//button.addActionListener(new BookButtonListener());
// bookButtons.add(button);
//}
// Scroll Pane
bookList = new JScrollPane();
bookList.setBorder(BorderFactory.createTitledBorder("Book List"));
bookList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
bookList.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(bookList,BorderLayout.CENTER);
bookList.add(bookButtons);
}
private class loadButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String filename = new String(importField.getText());
library.loadLibraryFromCSV(filename);
}
}
}
However, I'm having an issue with the test button not showing up at all within the scroll pane. The panels are there but not the test button.
You can't "add" components to a JScrollPane, this isn't how they work. A JScrollPane uses a JViewport as it's primary component, which is then used to determine when the scrollbars should be used.
See How to Use Scroll Panes for more details
Instead of...
bookList = new JScrollPane();
//...
bookList.add(bookButtons);
simply do...
bookList = new JScrollPane(bookButtons);
//...
//bookList.add(bookButtons);

How do I lay out Input panel with multiple textfields and OK, CANCEL buttons?

I am trying to achieve the following effect in Java:
However, I am not sure what layout to use and how. FlowLayout obviously doesn't work. GridLayout won't work either because the first 4 rows are supposed to be 1 column rows, but the 5th row needs to have 2 columns.
This is my code so far:
public class DepositPanel extends JPanel
{
private JLabel cashL, checksL;
private JTextField cashTF, checksTF;
private JButton ok, cancel;
DepositPanel()
{
JPanel depositP = new JPanel();
depositP.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 2));
depositP.setPreferredSize(new Dimension(250, 85));
JTextField cashTF = new JTextField(22);
JTextField checksTF = new JTextField(22);
JLabel cashL = new JLabel("Cash:");
JLabel checksL = new JLabel("Checks:");
ok = new JButton("OK");
cancel = new JButton("CANCEL");
depositP.add(cashL);
depositP.add(cashTF);
depositP.add(checksL);
depositP.add(checksTF);
depositP.add(ok);
depositP.add(cancel):
}
}
You could try with combinations of Layouts, 2 JPanels, 1 for buttons and 1 for fields, button panel with FlowLayout and fields panel with BoxLayout. And adding them to the frame. (I did a JFrame for testing, but you can change it to a JPanel and add that panel to your JFrame). Just be sure to have only 1 JFrame, see The use of multiple JFrames, Good / Bad Practice.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class DepositExample {
JFrame frame;
JPanel buttonPane, fieldsPanel;
JLabel cash, checks;
JTextField cashField, checksField;
JButton ok, cancel;
DepositExample() {
frame = new JFrame("Deposit");
buttonPane = new JPanel();
fieldsPanel = new JPanel();
cash = new JLabel("Cash");
checks = new JLabel("Checks");
cashField = new JTextField("");
checksField = new JTextField("");
ok = new JButton("OK");
cancel = new JButton("Cancel");
fieldsPanel.setLayout(new BoxLayout(fieldsPanel, BoxLayout.PAGE_AXIS));
buttonPane.setLayout(new FlowLayout());
fieldsPanel.add(cash);
fieldsPanel.add(cashField);
fieldsPanel.add(checks);
fieldsPanel.add(checksField);
buttonPane.add(ok);
buttonPane.add(cancel);
frame.add(fieldsPanel, BorderLayout.PAGE_START);
frame.add(buttonPane, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
new DepositExample();
}
}
To get some more spacing between components you can add EmptyBorders as recommended by #LuxxMiner in his comment below.
In this case you can use a JOptionPane to build a simple panel for you:
JTextField firstName = new JTextField(10);
JTextField lastName = new JTextField(10);
Object[] msg = {"First Name:", firstName, "Last Name:", lastName};
result = JOptionPane.showConfirmDialog(
frame,
msg,
"Use default layout",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
The only problem with this approach is that the focus will be on a button, not the first name text field.
So to solve this problem you can check out the RequestFocusListener found in Dialog Focus which will cause focus to be placed on the first name text field once the dialog is displayed.
JTextField firstName = new JTextField(10);
firstName.addAncestorListener( new RequestFocusListener() );
Although for more complex layouts it is better to create one or more panels each using an appropriate layout manager for the requirement.
There are many ways to achieve a layout like this. The first thing you need to get used to, is that its often simpler to split up different requirements into different containers using different layout managers.
If you separate the two buttons into their own panel and treat that panel with the buttons as "just another line" in the window, you can basically just use a GridLayout with a single column. The panel with the buttons could then use a FlowLayout to place the buttons side by side.
Try this:
public class Window extends JFrame{
....
}
JLabel example;
//Constructor
public Window(){
example = new JLabel("Sample text");
example.setBounds(x,y,width,height)
//JComponent...
setLayout(null);
setSize(width,height);
setVisible(true);
}
Without the JPanel you can specify the x and y coordinates

positioning different component in java GUI

im trying to design java GUI frame which contains labels, textfields, radio buttons and button..
i want to position each component in specific place tried setBounds() but it didn't work..
also im trying to change background color of the frame using getContentPane().setBackground(Color.white) and setBackground(Color.white) but didnt work too.
how to do it ?
this is my code :
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class test extends JFrame{
public static void main(String[] args) {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("WHO IS THE WINNER");
guiFrame.setSize(700,500);
guiFrame.setLocationRelativeTo(null);
final JPanel first = new JPanel();
JLabel un = new JLabel("UserName:");
JTextField textField = new JTextField(20);
JLabel sn = new JLabel("Server Name:");
JTextField textField2 = new JTextField(20);
un.setLabelFor(textField);
sn.setLabelFor(textField2);
first.add(un);
first.add(textField);
first.add(sn);
first.add(textField2);
final JPanel second = new JPanel();
JLabel level = new JLabel("Level:");
JLabel score = new JLabel("Score:");
JLabel question = new JLabel("Question:");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox radio1 = new Checkbox("True", radioGroup,false);
Checkbox radio2 = new Checkbox("False", radioGroup,true);
second.add(score);
second.add(level);
second.add(question);
second.add(radio1);
second.add(radio2);
JButton next = new JButton( "Next");
next.addActionListener(
new ActionListener() {
#Override public void actionPerformed(ActionEvent event) {
first.setVisible(false);
} });
guiFrame.add(first, BorderLayout.NORTH);
guiFrame.add(second, BorderLayout.CENTER);
guiFrame.add(next,BorderLayout.SOUTH);
guiFrame.setVisible(true);
}
}
for the positioning for example i want the first label and text field under them the other label and text field not beside them.. same for other labels and radio buttons i don't want them it be beside each other i want o give them a specific position to be in..
can someone please help ?
Thanks :)
This answer is just for Eclipse IDE.
An easy way to place all the widgets is doing it from the Design tab, placed at the bottom-left side of the window. Just change from Source perspective to Design perspective. It will open a simple panel with everything you need. Just drag the different widgets and place them in their position.
To change the background of the frame, do it from the properties of the frame in the Design tab or add the following code to the constructor of the panel:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);

Java Swing UI Layout

I am creating a basic user interface in Swing and was hoping for some help. Below is a screenshot of what I am trying to achieve:
My code currently is as follows:
package testui;
import java.awt.Container;
import javax.swing.*;
public class TestUI{
private JTextField outputArea = new JTextField();
private JTextField errorReportArea = new JTextField();
private JPanel inputPanel = new JPanel();
private JLabel nameLabel = new JLabel("Item Name");
private JLabel numberLabel = new JLabel("Number of units (or Volume in L)");
private JLabel priceLabel = new JLabel("Price per unit (Or L) in pence");
private JTextField nameField = new JTextField(10);
private JTextField numberField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JButton addVolumeButton = new JButton("Add by Volume");
private JButton addNumberButton = new JButton("Add by number of units");
public TestUI() {
JFrame frame = new JFrame("Fuel Station");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outputArea.setEditable(false);
errorReportArea.setEditable(false);
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));
inputPanel.add(nameLabel);
inputPanel.add(nameField);
inputPanel.add(numberLabel);
inputPanel.add(numberField);
inputPanel.add(priceLabel);
inputPanel.add(priceField);
inputPanel.add(addVolumeButton);
inputPanel.add(addNumberButton);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(outputArea);
contentPane.add(errorReportArea);
contentPane.add(inputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
TestUI test1 = new TestUI();
}
}
Which looks like this:
So what I would like to do is set a specific size for the top two JTextFields, as the top one will contain multiple lines of text, and the one below will contain just one line of text. I am unsure how to do this without using setSize, as I have been told it is bad coding practice to use this.
I would also like to add some padding between the JLabels, JTextFields and JButtons in the bottom JPanel.
If anyone could give me some suggestions on resizing these components I would be most grateful
Since you want your textfields to be multilined, use JTextAreas. JTextFields are single lined only.
Your components are right next to each other which isn't the same look as your intended outcome. There may be some method that gives your components some breathing room before you would call frame.pack()
Look for any method that can make a component fill the total amount of room it's given; especially when you want something to fill a large chunk of space.
You can set the number of columns instead of using setSize() for your JTextFields/JTextAreas. Just saying.
Reviewing all of Java's Layout Managers would help you get a grasp of the capabilities and use cases for each layout manager
There are a few layout managers that are flexible enough to perform this, such as Mig, Gridbag, and SpringLayout.
In your case, you'd have the following constraints:
outputarea - south border constrained to be ###px from the north border of the contentPane
errorReportArea - north border constrained to be 0px from outputarea's south, and south border constrained to be 0px from inputPanel's north.
inputPanel - north border constrained to be ##px from the south border of the contentPane.
GUI builders such as WindowBuilder will allow you to do this pretty quickly. You just drop in the layout onto the contentPane and then set the constraints.
If you have to use a box layout look at the glue and rigidArea methods in Box. If you can use other layouts, go with those suggested by the other answers.
I have created a solution with the MigLayout manager.
Here are some recommendations:
Put application code outside the constructor; in the solution, the code
is placed in the initUI() method.
The application should be started on EDT by calling the
EventQueue.invokeLater(). (See the main() method of the provided solution.)
Use a modern, flexible layout manager: MigLayout, GroupLayout, or FormLayout.
Take some time to study them to fully understand the layout management process. It
is important have a good understanding of this topic.
Shorten the labels; use more descriptive tooltips
instead.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutSolution extends JFrame {
private JTextArea outputArea;
private JTextField errorReportField;
private JLabel nameLabel;
private JLabel numberLabel;
private JLabel priceLabel;
private JTextField nameField;
private JTextField numberField;
private JTextField priceField;
private JButton addVolumeButton;
private JButton addNumberButton;
public MigLayoutSolution() {
initUI();
}
private void initUI() {
setLayout(new MigLayout());
outputArea = new JTextArea(10, 20);
errorReportField = new JTextField(15);
nameLabel = new JLabel("Item name");
numberLabel = new JLabel("# of units");
numberLabel.setToolTipText("Number of units (or Volume in L)");
priceLabel = new JLabel("Price per unit");
priceLabel.setToolTipText("Price per unit (Or L) in pence");
nameField = new JTextField(10);
numberField = new JTextField(10);
priceField = new JTextField(10);
addVolumeButton = new JButton("AddVol");
addVolumeButton.setToolTipText("Add by Volume");
addNumberButton = new JButton("AddNum");
addNumberButton.setToolTipText("Add by number of units");
add(new JScrollPane(outputArea), "grow, push, wrap");
add(errorReportField, "growx, wrap");
add(nameLabel, "split");
add(nameField);
add(numberLabel);
add(numberField);
add(priceLabel);
add(priceField);
add(addVolumeButton);
add(addNumberButton);
pack();
setTitle("Fuel station");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutSolution ex = new MigLayoutSolution();
ex.setVisible(true);
}
});
}
}

JAVA - Can't add Text Field and Button to container

I'm trying to do a little program that use some buttons and text field.
I was able to create window with JPanel but don't have idea how to add button and text field
The code I'm using is:
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,SZEROKOSC,WYSOKOSC);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
panel.add(this);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextField pole = new JTextField(10);
JButton przycisk = new JButton("teasda");
przycisk.setPreferredSize(new Dimension(300, 350));
przycisk.setLayout(new BorderLayout());
panel.add(przycisk);
przycisk.setVisible(true);
pole.setBounds (300,300,200,200);
pole.setLayout(null);
pole.setVisible(true);
panel.add(pole);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
// addMouseListener(this);
}
You need to use the layout properly, when using border layout you need to tell it which border to use (, BorderLayout.NORTH or something), check out the tutorials at oracles page.
P.S. Think of how your naming your fields etc. Naming something "przycisk" just gives me a reason not to read the code further.
Thank You for help and sorry for Polish names(fixed already).
I was able to add Text Area with scroll.
Looks like problem was in panel.add(this); putted before button and text field.
From my understanding if panel.add(this) is set before panel.add(pole); then panel.add(this) is set in front and pole is added but not seen.
Below my actual working code:
...
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,WIDTH,HEIGHT);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextArea pole = new JTextArea();
pole.setLayout(null);
pole.setLineWrap(true);
//pole.setBackground(Color.BLACK);
pole.setEditable(false);
JScrollPane scroll = new JScrollPane(pole);
scroll.setBounds(25,250,500,300);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll);
panel.add(this);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
addMouseListener(this);
}
...
This code is from this site: Example of Java GUI
//Imports are listed in full to show what's being used
//could just import javax.swing.* and java.awt.* etc..
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GuiApp1 {
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
new GuiApp1();
}
public GuiApp1()
{
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Example GUI");
guiFrame.setSize(300,250);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//Options for the JComboBox
String[] fruitOptions = {"Apple", "Apricot", "Banana"
,"Cherry", "Date", "Kiwi", "Orange", "Pear", "Strawberry"};
//Options for the JList
String[] vegOptions = {"Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery", "Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish", "Shallot", "Spinach", "Swede"
, "Turnip"};
//The first JPanel contains a JLabel and JCombobox
final JPanel comboPanel = new JPanel();
JLabel comboLbl = new JLabel("Fruits:");
JComboBox fruits = new JComboBox(fruitOptions);
comboPanel.add(comboLbl);
comboPanel.add(fruits);
//Create the second JPanel. Add a JLabel and JList and
//make use the JPanel is not visible.
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
JList vegs = new JList(vegOptions);
vegs.setLayoutOrientation(JList.HORIZONTAL_WRAP);
listPanel.add(listLbl);
listPanel.add(vegs);
JButton vegFruitBut = new JButton( "Fruit or Veg");
//The ActionListener class is used to handle the
//event that happens when the user clicks the button.
//As there is not a lot that needs to happen we can
//define an anonymous inner class to make the code simpler.
vegFruitBut.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
//When the fruit of veg button is pressed
//the setVisible value of the listPanel and
//comboPanel is switched from true to
//value or vice versa.
listPanel.setVisible(!listPanel.isVisible());
comboPanel.setVisible(!comboPanel.isVisible());
}
});
//The JFrame uses the BorderLayout layout manager.
//Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
guiFrame.add(listPanel, BorderLayout.CENTER);
guiFrame.add(vegFruitBut,BorderLayout.SOUTH);
//make sure the JFrame is visible
guiFrame.setVisible(true);
}
}
For the future i will recommend you to use the extends JFrame so you can only write a gui like this without initialize a JFrame:
public class CalculatorGUI extends JFrame {
public CalculatorGUI() {
setTitle("Calculator");
setBounds(300, 300, 220, 200);
}}
I suggest you check out a couple of tutorials about how to create a Java Gui or sth.

Categories

Resources