JPanel doesn't wait for user input before moving on - java

I'm trying to make a program that will do some fairly simple calculations in a JPanel. One of the requirements is that it will repeat until the user says otherwise. Unfortunately when the JPanel opens it does not wait for any user input, but instead moves right on to the next thing (as I have yet written the part that asks the user if he would like to continue or quit, it's currently in an infinite while loop which means that new JPanels just keep opening continually until I stop the program). My question is: Why isn't the program waiting until the user presses the Okay button to move on?
Here is my main():
public class Driver extends JFrame{
public static void main(String args[]){
do{
new GUI();
while (!GUI.isButtonPressed()){
}
//int choice = JOptionPane.showConfirmDialog(null, "Default tax rate is 7.5%\nDefault discount rate is 10%.\nKeep these default values?", "Choose an Option", JOptionPane.YES_NO_OPTION);
//switch (choice){
//case JOptionPane.YES_OPTION: {
//SaleItem newItem = new SaleItem();
//break;
//}
//case JOptionPane.NO_OPTION: {
//new GUI();
//break;
//}
//}
}while(true);
}
and here is my GUI:
import javax.swing.*;
import java.awt.event.*;
public class GUI extends JFrame {
JPanel panel;
JLabel priceLabel;
JLabel discountLabel;
JLabel taxLabel;
JTextField taxTextField;
JTextField priceTextField;
JTextField discountTextField;
JButton okayButton;
JButton defaultsButton;
final int WINDOW_WIDTH = 300;
final int WINDOW_HEIGHT = 250;
boolean buttonPressed = false;
public boolean isButtonPressed() {
return buttonPressed;
}
public void setButtonPressed(boolean buttonPressed) {
this.buttonPressed = buttonPressed;
}
public GUI(){
super("Item Properties");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel(){
priceLabel = new JLabel("Enter the item price:");
priceTextField = new JTextField(10);
discountTextField = new JTextField(10);
discountLabel = new JLabel("Enter the discount percent:");
taxLabel = new JLabel("Enter the tax percent:");
taxTextField = new JTextField(10);
okayButton = new JButton("Okay");
okayButton.addActionListener(new ButtonListener());
defaultsButton = new JButton("Use Defaults");
defaultsButton.addActionListener(new ButtonListener());
panel = new JPanel();
panel.add(priceLabel);
panel.add(priceTextField);
panel.add(discountLabel);
panel.add(discountTextField);
panel.add(taxLabel);
panel.add(taxTextField);
panel.add(okayButton);
panel.add(defaultsButton);
}
private class ButtonListener implements ActionListener {
private boolean buttonPressed = false;
public void actionPerformed(ActionEvent event){
GUI.setButtonPressed(true);
SaleItem newItem = new SaleItem(Double.parseDouble(priceTextField.getText()), Double.parseDouble(discountTextField.getText()), Double.parseDouble(taxTextField.getText()));
}
}
The stuff about getButtonPressed() and isButtonPressed() and all that was me trying (unsuccessfully) to solve the problem on my own.
Thanks in advance for any help!

Unfortunately when the JPanel opens it does not wait for any user input,
Panels don't open. You add a panel to a frame or dialog. If you want something to "open" or "popup" then you use a JDialog.
SaleItem newItem = new SaleItem(...);
SaleItem should be a modal JDialog. Then the dialog will not close until the user clicks on button that you create to close the dialog. A dialog is created exactly the same way as you create a JFrame.

Related

Java Swing - manipulation of GUI

I've got probably trivial problem but I've spent hours in looking for answer.
I would like to create a button (ENTER button) that once clicked, removes certain components on the GUI (like numpad). The problem is that the class that defines instructions to do once button clicked doesn't see the components. I've tried to add implements ATM to this class but then the console returned very weird errors (when executing). Is there any 'clean' way to do this?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ATM extends JFrame{
// Container
int state = 0; // PIN screen
// ELEMENTS
JPanel container = new JPanel();
JTextArea display = new JTextArea("Please enter your PIN", 10, 50);
JTextField inputArea = new JTextField("");
JPanel buttons = new JPanel();
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton four = new JButton("4");
JButton five = new JButton("5");
JButton six = new JButton("6");
JButton seven = new JButton("7");
JButton eight = new JButton("8");
JButton nine = new JButton("9");
JButton zero = new JButton("0");
JButton clear = new JButton("Clear");
JButton enter = new JButton("Enter");
JButton quit = new JButton("Quit");
// EVENTS
ButtonPresser buttonPress = new ButtonPresser(inputArea, display);
EnterPresser enterPress = new EnterPresser(inputArea, display, state, buttons);
ATM(){
super("ATM Cash Machine");
buildGUI();
pack();
setVisible(true);
}
private void buildGUI(){
// EVENT BINDINGS
one.addActionListener(buttonPress);
two.addActionListener(buttonPress);
three.addActionListener(buttonPress);
four.addActionListener(buttonPress);
five.addActionListener(buttonPress);
six.addActionListener(buttonPress);
seven.addActionListener(buttonPress);
eight.addActionListener(buttonPress);
nine.addActionListener(buttonPress);
zero.addActionListener(buttonPress);
clear.addActionListener(buttonPress);
quit.addActionListener(buttonPress);
enter.addActionListener(enterPress);
// ELEMENT SETTINGS
inputArea.setEditable(false);
display.setEditable(false);
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
container.add(display);
container.add(inputArea);
// Numeric pad
buttons.setLayout(new GridLayout(5,3));
buttons.add(one);
buttons.add(two);
buttons.add(three);
buttons.add(four);
buttons.add(five);
buttons.add(six);
buttons.add(seven);
buttons.add(eight);
buttons.add(nine);
buttons.add(clear);
buttons.add(zero);
buttons.add(enter);
buttons.add(quit);
container.add(buttons);
add(container, BorderLayout.NORTH);
}
// Main method
public static void main(String[] args){
ATM atm = new ATM();
}
}
class ButtonPresser implements ActionListener{
private JTextField iField;
private JTextArea oArea;
ButtonPresser(JTextField in, JTextArea out){
iField = in;
oArea = out;
}
public void actionPerformed(ActionEvent e){
switch(e.getActionCommand()){
case "Quit":
System.exit(0);
break;
case "Clear":
iField.setText("");
break;
default:
String fieldText = iField.getText();
if(fieldText.length() < 4){
iField.setText(fieldText+e.getActionCommand());
}
break;
}
}
}
class EnterPresser implements ActionListener{
private JTextField iField;
private JTextArea oArea;
private int state;
private JPanel buttons;
private final String PIN = "1234";
EnterPresser(JTextField in, JTextArea out, int st, JPanel but){
iField = in;
oArea = out;
state = st;
buttons = but;
}
public void actionPerformed(ActionEvent e){
if(state == 0){
String fieldText = iField.getText();
if(fieldText.equals(PIN)){
iField.setText("");
state = 1;
uiState0To1();
}
}
}
public void uiState0To1(){
buttons.remove(one);
}
}
The solution to your problem is simple. You need some way for your ButtonPresser class to talk with your ATM class, this is a classic example of an Observer Pattern
The idea is, you would provide some kind of event notification that your ButtonPresser will trigger under certain conditions, then your ATM class would listen for those events, it would then decide what it should do based on those events.
It is not the responsibility of the ButtonPresser to modify the state of ATM, just so we're clear.
You're now moving into the realm of Model-View-Controller, which could provide you a means to utilise CardLayout, which will further reduce the overall complexity of your problem, but also isolate responsibility and decouple your code
I am not sure which components you are trying to remove, but your problem is pretty clear. All of the components defined in the ATM class are not public. One way to manipulate these components from other classes would be to set them public.
The simplest way is to declare them as "public static" and reference them statically through the ATM class. Depending on your case you may need multiple instances of ATM, in which case you would not declare them static.
Here is another question with good info: Difference between public static and private static variables

Make JOptionPane message dialog box dissappear after rendering

I am building a simple JFrame GUI requiring user input. If the user clicks the submit button, it checks for input then either renders a JOptionPane message telling the user to completely fill out the form, or it tells the user that the form submitted and closes the program. The problme is that if the user left blank fields, the message dialog box renders and only adds to the loop count if you try to close it and does not allow the user to return to the JFrame to apply input to the form.
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.util.Scanner.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author joel.ramsey
*/
public class JRStarPhase5 extends JFrame{
public static void main (String [] args) throws IOException {
JFrame window = new JRStarPhase5();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}//end main method
private boolean validationError;
private final JTextField fNameInput;
private final JTextField miInput;
private final JTextField lNameInput;
private final JTextField productChoiceInput;
private final JTextField licenseQuantityInput;
private final JTextField streetAddressInput;
private final JTextField cityInput;
private final JTextField stateInput;
private final JTextField zipInput;
private final JTextField phoneInput;
//constructor for JFrame
public JRStarPhase5(){
setTitle("JRStar Star Gaze Order Processing");
setSize (800,800);
Container pane = getContentPane();
GridLayout grid = new GridLayout(0,2);
pane.setLayout(grid);
JLabel fNameLabel = new JLabel ("First name:");
JLabel mi = new JLabel ("Middle initial:");
JLabel lNameLabel = new JLabel ("Last name:");
JLabel productChoice = new JLabel ("Star Gaze version:");
JLabel licenseQuantity = new JLabel ("License quantity:");
JLabel streetAddress = new JLabel ("Street address:");
JLabel city = new JLabel ("City:");
JLabel state = new JLabel ("State abbrev:");
JLabel zip = new JLabel ("Zip code:");
JLabel phone = new JLabel ("Phone Number:");
this.fNameInput = new JTextField(15);
this.miInput = new JTextField (1);
this.lNameInput = new JTextField (15);
this.productChoiceInput = new JTextField (1);
this.licenseQuantityInput = new JTextField (2);
this.streetAddressInput = new JTextField (20);
this.cityInput = new JTextField (20);
this.stateInput = new JTextField (2);
this.zipInput = new JTextField (5);
this.phoneInput = new JTextField (10);
//add as last buttons
JButton submit = new JButton("Submit");
SubmitButtonHandler sbh = new SubmitButtonHandler();
submit.addActionListener(sbh);
JButton clear = new JButton("Clear");
ClearButtonHandler cbh = new ClearButtonHandler();
clear.addActionListener(cbh);
pane.add(fNameLabel);
pane.add(fNameInput);
pane.add(mi);
pane.add(miInput);
pane.add(lNameLabel);
pane.add(lNameInput);
pane.add(productChoice);
pane.add(productChoiceInput);
pane.add(licenseQuantity);
pane.add(licenseQuantityInput);
pane.add(streetAddress);
pane.add(streetAddressInput);
pane.add(city);
pane.add(cityInput);
pane.add(state);
pane.add(stateInput);
pane.add(zip);
pane.add(zipInput);
pane.add(phone);
pane.add(phoneInput);
//add last
pane.add(submit);
pane.add(clear);
}//end constructor
private class SubmitButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
validationError = (fNameInput.getText().equals("")||
miInput.getText().equals("")||
lNameInput.getText().equals("")||
streetAddressInput.getText().equals("")||
cityInput.getText().equals("")||
stateInput.getText().equals("")||
zipInput.getText().equals("")||
phoneInput.getText().equals(""));
for (int n=1; n<3; n++){
if (validationError){
if (n == 3){
System.exit(0);
}
JOptionPane.showMessageDialog(null,"Please complete each field within the order form.");
}
else break;
}
if (validationError = false)
JOptionPane.showMessageDialog(null,"Your order has been submitted!");
System.exit(0);
}
}//end submit
private class ClearButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
fNameInput.setText("");
miInput.setText("");
lNameInput.setText("");
productChoiceInput.setText("");
licenseQuantityInput.setText("");
streetAddressInput.setText("");
cityInput.setText("");
stateInput.setText("");
zipInput.setText("");
phoneInput.setText("");
}
}//end clear
}//end main class
I honestly don't know what else you expected (no offense).
Swing is a event driven environment. An event occurs, you react to it...
The loop will execute within the context of the EDT to start with, meaning that there is no way a user could actually close the dialog, correct the error and try to re-submit.
Even if it did, the loop does not allow for any opportunity for the validationError variable to be re-evaluated, meaning it will always be what it was originally set to earlier in the method (lets assume true for now)...
for (int n = 1; n < 3; n++) {
if (validationError) {
if (n == 3) {
System.exit(0);
}
JOptionPane.showMessageDialog(null, "Please complete each field within the order form.");
} else {
break;
}
}
if (validationError = false) {
JOptionPane.showMessageDialog(null, "Your order has been submitted!");
}
System.exit(0);
So basically you have a death trap, there is simply no way to escape...
Let's take another approach. Rather than using a hard-loop, like for or while, we can create a soft loop, whereby, each time the method is executed and the form is invalid, we update a counter, until that counter runs out...
// How many times retries has the user used...
private int retries = 0;
/*...*/
public void actionPerformed(ActionEvent e) {
validationError = (fNameInput.getText().equals("")
|| miInput.getText().equals("")
|| lNameInput.getText().equals("")
|| streetAddressInput.getText().equals("")
|| cityInput.getText().equals("")
|| stateInput.getText().equals("")
|| zipInput.getText().equals("")
|| phoneInput.getText().equals(""));
if (validationError) {
retries++;
if (retries < 3) {
JOptionPane.showMessageDialog(this, "Please complete each field within the order form.");
} else {
JOptionPane.showMessageDialog(this, "You've used up all your tries...");
System.exit(0);
}
} else {
JOptionPane.showMessageDialog(this, "Your order has been submitted!");
System.exit(0);
}
}
You may also like to have a read of Validating Input from the How to use the focus subsystem tutorial...

Closing a JFrame after a button is clicked Java

Hello I am writing a sort of Menu for an encryption program I am writing. I finished the core of it, and now i want to try to create a GUI for it. Here is the code for the first Menu:
package matrix_with_GUI;
import javax.swing.*;
import java.awt.event.* ;
import java.awt.* ;
public class Main_Menu extends JFrame implements ActionListener{
private JButton action1 = new JButton ("");
private JButton action2 = new JButton ("");
private JPanel pane = new JPanel();
private JLabel lbl;
public static void main(String[] args) {
Main_Menu main = new Main_Menu();
}
public Main_Menu(){
super();
JPanel pane=new JPanel();
setTitle ("Start Menu") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
action1 = new JButton("Start");
action2 = new JButton("Exit");
lbl = new JLabel ("Welcome to the Matrix Encoder/Decoder!!!");
setLayout(new FlowLayout());
add (lbl) ;
add(action1, BorderLayout.CENTER);
action1.addActionListener (this);
add(action2, BorderLayout.CENTER);
action2.addActionListener (this);
}
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
OptionsMenu x = new OptionsMenu();
if (event.getSource() == action1)
{
System.exit(0);
x.OptionsMenu();
}
else if(event.getSource() == action2){
System.exit(0);
}
}
}
When the Start Button is clicked, the new menu comes up all fine and good, but the first menu stays open. Is there a way to close this first menu AND open the second menu with the first button click? I'm very new to GUI so the simplest solution would be very helpful. On a side note is there a simple way to move the Start button to the next line? Thanks
You have 2 options: you can use a Window Listener, or you can use the dispose() method. To do the dispose() just type
* This is better to be used with subframes and 2nd level windows.*
this.dispose();
or check this link for using the window listener
Closing JFrame
In order to close the Main_Menu, you can just call its dispose method:
this.dispose();
instead of calling System.exit(0), which will terminate the JVM altogether.

How does JFileChooser return the exit value?

A typical way to use JFileChooser includes checking whether user clicked OK, like in this code:
private void addModelButtonMouseClicked(java.awt.event.MouseEvent evt) {
JFileChooser modelChooser = new JFileChooser();
if(modelChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ){
File selectedFile = modelChooser.getSelectedFile();
if(verifyModelFile(selectedFile)){
MetModel newModel;
newModel = parser.parse(selectedFile, editedCollection.getDirectory() );
this.editedCollection.addModel(newModel);
this.modelListUpdate();
}
}
}
I tried to mimic this behavior in my own window inheriting JFrame. I thought that this way of handling forms is more convenient than passing collection that is to be edited to the new form. But I have realized that if I want to have a method in my JFrame returning something like exit status of it I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window.
So, how does showOpenDialog() work? When I tried to inspect the implementation, I found only one line methods with note "Compiled code".
I tried to mimic this behavior in my own window inheriting JFrame.
JFrame is not a modal or 'blocking' component. Use a modal JDialog or JOptionPane instead.
E.G.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/** Typical output:
[JTree, colors, violet]
User cancelled
[JTree, food, bananas]
Press any key to continue . . .
*/
class ConfirmDialog extends JDialog {
public static final int OK_OPTION = 0;
public static final int CANCEL_OPTION = 1;
private int result = -1;
JPanel content;
public ConfirmDialog(Frame parent) {
super(parent,true);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
content = new JPanel(new BorderLayout());
gui.add(content, BorderLayout.CENTER);
JPanel buttons = new JPanel(new FlowLayout(4));
gui.add(buttons, BorderLayout.SOUTH);
JButton ok = new JButton("OK");
buttons.add(ok);
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = OK_OPTION;
setVisible(false);
}
});
JButton cancel = new JButton("Cancel");
buttons.add(cancel);
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = CANCEL_OPTION;
setVisible(false);
}
});
setContentPane(gui);
}
public int showConfirmDialog(JComponent child, String title) {
setTitle(title);
content.removeAll();
content.add(child, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getParent());
setVisible(true);
return result;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Test ConfirmDialog");
final ConfirmDialog dialog = new ConfirmDialog(f);
final JTree tree = new JTree();
tree.setVisibleRowCount(5);
final JScrollPane treeScroll = new JScrollPane(tree);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Choose Tree Item");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = dialog.showConfirmDialog(
treeScroll, "Choose an item");
if (result==ConfirmDialog.OK_OPTION) {
System.out.println(tree.getSelectionPath());
} else {
System.out.println("User cancelled");
}
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(b);
p.setBorder(new EmptyBorder(50,50,50,50));
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
I guess you wait for the user to click some button by constantly checking what button is pressed.
"I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window."
May be you should use evens to get notified, when the user clicks on something, not waiting for them to press the button - maybe there is some OnWindowExit event?
Or maybe something like this:
MyPanel panel = new MyPanel(...);
int answer = JOptionPane.showConfirmDialog(
parentComponent, panel, title, JOptionPane.YES_NO_CANCEL,
JOptionPane.PLAIN_MESSAGE );
if (answer == JOptionPane.YES_OPTION)
{
// do stuff with the panel
}
Otherwise you might see how to handle window events, especially windowClosing(WindowEvent) here

Java tabs in GUI

I am hoping someone can spoon feed me this solution. It is part of my major lab for the class, and it really isn't giving me too much since I just don understand how to make a GUI with tabs. I can make a regular program with some sort of GUI, but I've been searching and reading and can't put 2 and 2 because of the whole class part and declaring the private variables. So what I am asking is if someone can make me a main GUI with 5 tabs and put my code into 1 tab so I can learn and put the rest of my codes into the other 4 tabs. So I hope you don't think I want you to give me code when I have the code, I just don't really get the tabs, and we haven't gone over it in class. Here is the code with its own gui, I hope what I type makes sense. I learn code by seeing, and this will help me a bunch.
package landscape;
import javax.swing.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.text.DecimalFormat;
public class Landscape extends JFrame {
private JFrame mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JLabel lengthLabel;
private JTextField widthField;
private JLabel widthLabel;
private JTextField depthField;
private JLabel depthLabel;
private JTextField volumeField;
private JLabel volumeLabel;
private JRadioButton builtIn;
private JRadioButton above;
private JTabbedPane panel;
public Landscape()
{
JTabbedPane tabs=new JTabbedPane();
tabs.addTab("Pool", panel);//add a tab for the panel with the title "title"
//you can add more tabs in the same fashion - obviously you can change the title
//tabs.addTab("another tab", comp);//where comp is a Component that will occupy the tab
mainFrame.setContentPane(tabs);//the JFrame will now display the tabbed pane
mainFrame.setSize(265,200);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
JPanel panel = new JPanel();//FlowLayout is default
//Pool
panel.setOpaque(false);//this tells the panel not to draw its background; looks nicer under LAFs where the background inside a tab is different from that of JPanel
panel.add(builtIn);
panel.add(above);
panel.add(lengthLabel);
panel.add(lengthField);
panel.add(widthLabel);
panel.add(widthField);
panel.add(depthLabel);
panel.add(depthField);
panel.add(volumeLabel);
panel.add(volumeField);
panel.add(calculateButton);
panel.add(exitButton);
//creating components
calculateButton = new JButton ("Calculate");
exitButton = new JButton ("Exit");
lengthField = new JTextField (5);
lengthLabel = new JLabel ("Enter the length of your pool: ");
widthField = new JTextField (5);
widthLabel = new JLabel ("Enter the width of your pool: ");
depthField = new JTextField (5);
depthLabel = new JLabel ("Enter the depth of your pool: ");
volumeField = new JTextField (5);
volumeLabel = new JLabel ("Volume of the pool: ");
//radio button
ButtonGroup buttonGroup = new ButtonGroup();
builtIn = new JRadioButton ("Built in");
buttonGroup.add(builtIn);
above = new JRadioButton ("Above");
buttonGroup.add(above);
exitButton.setMnemonic('x');
calculateButton.setMnemonic('C');
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); }
});
// create the handlers
calculateButtonHandler chandler = new calculateButtonHandler(); //instantiate new object
calculateButton.addActionListener(chandler); // add event listener
ExitButtonHandler ehandler = new ExitButtonHandler();
exitButton.addActionListener(ehandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
depthField.addFocusListener(fhandler);
}
class calculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat num = new DecimalFormat(", ###.##");
double width;
double length;
double depth;
double volume;
double volume2;
double height;
String instring;
instring = lengthField.getText();
if (instring.equals(""))
{
instring = "0";
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = widthField.getText();
if (instring.equals(""))
{
instring = "0";
widthField.setText("0");
}
width = Double.parseDouble(instring);
instring = depthField.getText();
if (instring.equals(""))
{
instring = "0";
depthField.setText("0");
}
depth = Double.parseDouble(instring);
volume = width * length * depth;
volumeField.setText(num.format(volume));
volume2 = width * length * depth;
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if(e.getSource() == lengthField || e.getSource() == widthField || e.getSource() == depthField)
{
volumeField.setText("");
}
else if (e.getSource() == volumeField)
{
volumeField.setNextFocusableComponent(calculateButton);
calculateButton.grabFocus();
}
}
public void focusLost1(FocusEvent e)
{
if(e.getSource() == widthField)
{
widthField.setNextFocusableComponent(calculateButton);
}
}
public void focusLost(FocusEvent e)
{
if(e.getSource() == depthField)
{
depthField.setNextFocusableComponent(calculateButton);
}
}
}
public static void main(String args[])
{
Landscape app = new Landscape();
}
}
Instead of getting the content pane and adding to it, just create a new JPanel and add your stuff to that. Then, add the panel to a new JTabbedPane with whatever title you want, and set the content pane of the JFrame to be the tabbed pane.
Here is a simple example of what you would do:
JPanel panel=new JPanel();//FlowLayout is default
panel.setOpaque(false);//this tells the panel not to draw its background; looks nicer under LAFs where the background inside a tab is different from that of JPanel
panel.add(builtIn);
panel.add(above);
//...you get the picture; add all the stuff you already do, just use panel instead of c
JTabbedPane tabs=new JTabbedPane();
tabs.addTab("title", panel);//add a tab for the panel with the title "title"
//you can add more tabs in the same fashion - obviously you can change the title
tabs.addTab("another tab", comp);//where comp is a Component that will occupy the tab
mainFrame.setContentPane(tabs);//the JFrame will now display the tabbed pane
You can leave the rest of your code how it is and it should work fine.
The tutorial and its demo are pretty straight forward examples.

Categories

Resources