when i select something in combobox :
it show joptionPane Dialog box wiht two inputs.
here i want to first focusing amount field and then, when i entered in amount field its goes to no of App field then enter go to OK .
Here is my code for JOption Dialog:
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Amount:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("No of App:"));
myPanel.add(yField);
int value = 0;
xField.requestFocus();
int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter Amount and No.of app", JOptionPane.OK_CANCEL_OPTION);
You simply try to focus a component which is not layout in a window.
Replace
xField.requestFocus();
by
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xField.requestFocusInWindow();
}
});
You can create your own JDialog on the event that an item has changed to a new item. Then, you can get values entered in the JDialog and appropriately set the information in your parent. If you want to change the order of focus, use a custom focus policy. If you want to change the traversal focus key to the Enter key, you should re-map the key so that it reacts the same as the Tab key. There are several resources online and on this site with information on how to do that.
You should note that the default focus traversal policy is dependent on the order in which you add you elements to your content panel.
I have created a simple example for you on using a JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class RankSelection extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RankSelection frame = new RankSelection();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public RankSelection() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"Slave", "Peasant", "Minion", "Knight", "Bishop", "Prince", "Coder King"}));
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
Amount amount = new Amount();
textField.setText(Integer.toString((Integer) amount.getStinkiness().getValue()));
}
}
});
contentPane.add(comboBox, BorderLayout.CENTER);
JLabel lblYourRank = new JLabel("Your Rank");
contentPane.add(lblYourRank, BorderLayout.NORTH);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
JLabel lblYourStinkiness = new JLabel("Your Stinkiness:");
panel.add(lblYourStinkiness);
textField = new JTextField();
textField.setEditable(false);
textField.setEnabled(false);
textField.setText("0");
panel.add(textField);
textField.setColumns(10);
pack();
}
}
The custom JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Amount extends JDialog {
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JSpinner amount;
private JSpinner stinkiness;
public Amount() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
JLabel lblAmount = new JLabel("Amount:");
amount = new JSpinner();
JLabel lblStinkiness = new JLabel("Stinkiness:");
stinkiness = new JSpinner();
contentPanel.add(lblAmount);
contentPanel.add(amount);
contentPanel.add(lblStinkiness);
contentPanel.add(stinkiness);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
pack();
setVisible(true);
}
public JSpinner getAmount() {
return amount;
}
public JSpinner getStinkiness() {
return stinkiness;
}
}
Related
I am trying to making a calculator.
Here the user can add multiple JTextFields to take his/her desired input with just one button click.
Now I want that the user will take the input in multiple JTextFields added by him and on clicking the Result button will show the sum of all. But I am always getting 0 as output.
Code:
public class Button extends JFrame {
private JPanel contentPane;
private JButton btnAdd;
private JButton btnResult;
private JTextField resultField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Button frame = new Button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Button() {
initComponents();
}
static JTextField field = null;
//static JTextField fields[] = new JTextField[10];
private static int y = 0;
ArrayList<String> arr = new ArrayList<String>();
int ans, sum = 0;
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 527, 414);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field = new JTextField();
field.setBounds(45, y += 60, 284, 32);
field.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(field);
contentPane.revalidate();
contentPane.repaint();
}
});
btnAdd.setBounds(170, 341, 89, 23);
contentPane.add(btnAdd);
btnResult = new JButton("Result");
btnResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < arr.size(); i++) {
arr.add(field.getText());
sum += Integer.parseInt(arr.get(i));
}
resultField.setText(String.valueOf(sum));
}
});
btnResult.setBounds(383, 306, 89, 23);
contentPane.add(btnResult);
resultField = new JTextField();
resultField.setBounds(361, 275, 129, 20);
contentPane.add(resultField);
resultField.setColumns(10);
}
}
Please help how can I find the correct output?
Suggestions:
Again, when you create a data-entry text field, add it to the GUI and add it to an ArrayList of the data entry field type.
Then in the result button's ActionListener, iterate through this list using a for loop.
Inside of the for loop, get the entry field, get its text (via .getText() if using a JTextField), parse it to number via Integer.parseInt(...), and add it to a sum variable that is initialized to 0 prior to the for loop. Then display the result after the loop.
Also,
Best to use JSpinners that use a SpinnerNumberModel such as JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1)); instead of JTextField for number entry. This will limit the user to entering numbers only, and won't allow non-numeric text entry, a danger inherent in your current design.
Having to add your entry fields by button may be an over-complication
But if it is necessary, then best to add the spinners (or text fields if you must) to a JPanel that uses a proper layout manager, such a new GridLayout(0, 1) (variable number of rows, 1 column) and then add that to a JScrollPane so that you can see as many fields as has been entered.
If using a JSpinner, then you don't even need a "calculate result" button, since if you add a ChangeListener to each JSpinner, you can calculate the result on the fly whenever a spinner has had its data changed.
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Button2 extends JPanel {
private List<JSpinner> spinnerList = new ArrayList<>();
private JButton resultButton = new JButton("Result");
private JButton addEntryFieldBtn = new JButton("Add Entry Field");
private JTextField resultField = new JTextField(6);
private JPanel fieldPanel = new JPanel(new GridLayout(0, 1, 4, 4));
public Button2() {
resultField.setFocusable(false);
resultButton.addActionListener(e -> calcResult());
resultButton.setMnemonic(KeyEvent.VK_R);
addEntryFieldBtn.addActionListener(e -> addEntryField());
JPanel topPanel = new JPanel();
topPanel.add(addEntryFieldBtn);
topPanel.add(resultButton);
topPanel.add(new JLabel("Result:"));
topPanel.add(resultField);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(fieldPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(centerPanel);
scrollPane.setPreferredSize(new Dimension(300, 300));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane);
}
private void calcResult() {
int sum = 0;
for (JSpinner spinner : spinnerList) {
sum += (int) spinner.getValue();
}
resultField.setText(String.valueOf(sum));
}
private void addEntryField() {
JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinner.addChangeListener(evt -> {
calcResult();
});
fieldPanel.add(spinner);
spinnerList.add(spinner);
revalidate();
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Button2 mainPanel = new Button2();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
I want to know how to add components dynamically to a JDialog. I know there is a similar question on SO here, but as you can see, I have his solution as a part of my code.
So the idea is that on click of the button, I need to add a component on the dialog. The sample code is below:
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
Test test = new Test();
test.createDialog();
}
public void createDialog() {
DynamicDialog dialog = new DynamicDialog(this);
dialog.setSize(300, 300);
dialog.setVisible(true);
}
}
class DynamicDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
public DynamicDialog(final JFrame owner) {
super(owner, "Dialog Title", Dialog.DEFAULT_MODALITY_TYPE);
final JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createRigidArea(new Dimension(3, 10)));
panel.add(createLabel("Click on add"));
panel.add(Box.createRigidArea(new Dimension(23, 10)));
panel.add(createLabel("To add another line of text"));
panel.add(Box.createHorizontalGlue());
mainPanel.add(panel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(Box.createHorizontalGlue());
JButton button = new JButton();
button.setText("Add another line");
buttonPanel.add(button);
mainPanel.add(buttonPanel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
Container contentPane = owner.getContentPane();
JPanel _panel = new JPanel();
_panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
_panel.add(Box.createHorizontalGlue());
_panel.add(createLabel("Added!"));
contentPane.add(_panel);
contentPane.validate();
contentPane.repaint();
owner.pack();
}
});
pack();
setLocationRelativeTo(owner);
this.add(mainPanel);
}
JLabel createLabel(String name) {
JLabel label = new JLabel(name);
return label;
}
}
If you add it to the main panel it will work, you were adding it to the content pane of the frame which it seems it does not show up anywhere.
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JPanel _panel = new JPanel();
_panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
_panel.add(Box.createHorizontalGlue());
_panel.add(createLabel("Added!"));
mainPanel.add(_panel);
mainPanel.validate();
mainPanel.repaint();
owner.pack();
}
})
I need to take all the textField, comboBox, jlst, and jslider input from the first frame and make it into a summary in the second frame after the Submit button is picked. I can't figure out the best way to do this. My assignment requires a popup second frame with a textArea and exit button that brings you back to the first frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
public class Ch10Asg extends JFrame
{
private String[] flightNames = {"342", "4324", "939", "104", "222"};
private String[] cardTypes ={"Mastercard", "Visa", "American Express", "Discover"};
private String[] Dates ={"8/1/2013", "8/2/2013", "8/3/2013", "8/4/2013", "8/5/2013"};
private JTextField jtfFirst = new JTextField(10);
private JTextField jtfLast = new JTextField(10);
private JTextField jtfAddress = new JTextField(15);
private JTextField jtfCity = new JTextField(15);
private JTextField jtfState = new JTextField(2);
private JTextField jtfZip = new JTextField(5);
private JTextField jtfCard = new JTextField(16);
private JComboBox jcbo = new JComboBox(flightNames);
private JComboBox jcbcctype = new JComboBox(cardTypes);
private JList jlst = new JList(Dates);
private JSlider jsldHort = new JSlider(JSlider.HORIZONTAL,0,4,0);
private JButton jbtExit = new JButton ("EXIT");
private JButton jbtClear = new JButton ("CLEAR");
private JButton jbtSubmit = new JButton ("SUBMIT");
private JTextField jtfStart = new JTextField();
private JTextField jtfEnd = new JTextField();
public Ch10Asg()
{
JPanel p1 = new JPanel(new GridLayout(3,1));
p1.add(new JLabel("First Name"));
p1.add(jtfFirst);
p1.add(new JLabel("Last Name"));
p1.add(jtfLast);
p1.add(new JLabel("Address"));
p1.add(jtfAddress);
p1.add(new JLabel("City"));
p1.add(jtfCity);
p1.add(new JLabel("State"));
p1.add(jtfState);
p1.add(new JLabel("ZIP"));
p1.add(jtfZip);
JPanel p2 = new JPanel(new GridLayout(3,1));
p2.add(new JLabel("Select Flight Number"));
p2.add(jcbo);
p2.add(new JLabel("Select Date"));
p2.add(jlst);
p2.add(new JLabel("Select Time"));
jsldHort.setMajorTickSpacing(1);
jsldHort.setPaintTicks(true);
Hashtable<Integer, JLabel> labels = new Hashtable<Integer, JLabel>();
labels.put(0, new JLabel("4:00am"));
labels.put(1, new JLabel("5:00am"));
labels.put(2, new JLabel("8:00am"));
labels.put(3, new JLabel("11:00am"));
labels.put(4, new JLabel("5:00pm"));
jsldHort.setLabelTable(labels);
jsldHort.setPaintLabels(true);
p2.add(jsldHort);
JPanel p4 = new JPanel(new GridLayout(3,1));
p4.add(new JLabel("Starting City"));
p4.add(jtfStart);
p4.add(new JLabel("Ending City"));
p4.add(jtfEnd);
p4.add(new JLabel("Select Card Type"));
p4.add(jcbcctype);
p4.add(new JLabel("Enter Number"));
p4.add(jtfCard);
p4.add(jbtExit);
p4.add(jbtClear);
p4.add(jbtSubmit);
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.CENTER);
add(p4, BorderLayout.SOUTH);
jbtExit.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}});
jbtClear.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
jtfFirst.setText("");
jtfLast.setText("");
jtfAddress.setText("");
jtfCity.setText("");
jtfState.setText("");
jtfZip.setText("");
jtfCard.setText("");
}});
jbtSubmit.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
new Infopane(jtfFirst.getText());
//dispose();
}});
}//ENDOFCONSTRUCTOR
public static void main(String[] args)
{
Ch10Asg frame = new Ch10Asg();
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Flights");
frame.setVisible(true);
frame.setSize(700,450);
}//ENDOFMAIN
}//ENDOFCLASS
class Infopane extends JFrame
{
private JTextArea Info = new JTextArea();
private JButton jbtExit1 = new JButton ("EXIT");
public Infopane(String jtfFirst)
{
JPanel s1 = new JPanel();
add(Info, BorderLayout.NORTH);
//Info.setFont(new Font("Serif", Font.PLAIN, 14));
Info.setEditable(false);
JScrollPane scrollPane = new JScrollPane(Info);
//setLayout(new BorderLayout(5,5));
add(scrollPane);
add(jbtExit1, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Flight Summary");
setVisible(true);
setSize(700,450);
jbtExit1.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}});
}
}
Suggestions:
The second window shouldn't be a second JFrame but rather a modal JDialog since it truly is a dialog of the first window. This way, you don't have to fret about the second window closing the entire application when it is closed.
You already have an idea of what you should be doing -- passing information from one object to another -- since you're passing the String held by the first window's first name's JTextField into the second class: jtfFirst.getText()
Instead of passing just one JTextField's text, consider creating a third data class that holds all the information that you want to pass from one class to the other, create an object of this in the submit's ActionListener, and pass it into the new class.
Alternatively, you could give your first class getter methods, and just pass an instance of the first object into the second object, allowing the second object to extract info from the first by calling its getter methods.
Edit
For example here are snippets of a code example that works. The main JPanel is called MainPanel:
class MainPanel extends JPanel {
// my JTextFields
private JTextField fooField = new JTextField(10);
private JTextField barField = new JTextField(10);
public MainPanel() {
add(new JLabel("Foo:"));
add(fooField);
add(new JLabel("Bar:"));
add(barField);
add(new JButton(new AbstractAction("Submit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent evt) {
DialogPanel dialogPanel = new DialogPanel(MainPanel.this);
// code deleted....
// create and show a JDialog here
}
}));
add(new JButton(new AbstractAction("Exit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((JButton)e.getSource());
win.dispose();
}
}));
}
// getter methods to get information held in the fields.
public String getFooText() {
return fooField.getText();
}
public String getBarText() {
return barField.getText();
}
}
And in the dialog panel:
class DialogPanel extends JPanel {
private JTextArea textarea = new JTextArea(10, 15);
private MainPanel mainPanel;
public DialogPanel(MainPanel mainPanel) {
this.mainPanel = mainPanel; // actually don't even need this in your case
// extract the information from the origianl class
textarea.append("Foo: " + mainPanel.getFooText() + "\n");
textarea.append("Bar: " + mainPanel.getBarText() + "\n");
add(new JScrollPane(textarea));
add(new JButton(new AbstractAction("Exit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((JButton)e.getSource());
win.dispose();
}
}));
}
}
I have to make a simple program and the GUI would look like this:
,,,,,,,,,,
| Read | <---a Button
``````````
name |``````````| <---a Textfield
``````````
|
|
a Label
My problem is how do I get the Label 'name' in the Vertical Box of Button 'Read' and text field` as the name and the text field are horizontal?
please DYM???
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BoxStructAndJComponents {
private JLabel intro = new JLabel("The chosen name:");
private JFrame frame;
private JLabel name = new JLabel("JLabel");
public BoxStructAndJComponents() {
frame = new JFrame("JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = createUI();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public JPanel createUI() {
intro = new JLabel("The chosen name:");
intro.setLabelFor(name);
final JButton button = new JButton("Pick a new name...");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 10, 20));
intro.setAlignmentX(JComponent.CENTER_ALIGNMENT);
name.setAlignmentX(JComponent.CENTER_ALIGNMENT);
button.setAlignmentX(JComponent.CENTER_ALIGNMENT);
panel.add(intro);
panel.add(Box.createVerticalStrut(5));
panel.add(name);
panel.add(Box.createRigidArea(new Dimension(150, 10)));
panel.add(button);
return panel;
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
BoxStructAndJComponents bb = new BoxStructAndJComponents();
}
});
}
}
I would like to hide selected panel when a click a button. I have most of that working but when a panel is to false doesn't update.
This one of the things I've tried:
compsToExperiment.setVisible(mapVis);
updateUI();
private void updateUI() {
SwingUtilities.updateComponentTreeUI(this);
}
is this on the right track?
Any other ways of doing it ?
updateComponentTreeUI() doesn't force repaints. You must use the repaint method.
compsToExperiment.setVisible(mapVis);
frame.repaint();
where frame is the top window where the panel resides.
You does not have to do something fancy, other then calling setVisible(false); on the said JPanel. Below example is a proof of that :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InvisiblePanel
{
private JPanel centerPanel;
private JPanel footerPanel;
private JTextField addField;
private JTextField nameField;
private JTextField occField;
private JTextField phoneField;
private JLabel nameLabel;
private JLabel addLabel;
private JLabel occLabel;
private JLabel phoneLabel;
private JPanel contentPane;
private JButton hideButton;
private void displayGUI()
{
JFrame frame = new JFrame("Invisible Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setBackground(Color.RED.darker().darker());
contentPane.setLayout(new BorderLayout(5, 5));
nameLabel = new JLabel("Guarantee Name : ");
nameField = new JTextField();
addLabel = new JLabel("Address : ");
addField = new JTextField();
occLabel = new JLabel("Occupation : ");
occField = new JTextField();
phoneLabel = new JLabel("Phone : ");
phoneField = new JTextField();
centerPanel = new JPanel();
hideButton = new JButton("Hide");
hideButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (centerPanel.isShowing())
centerPanel.setVisible(false);
else
centerPanel.setVisible(true);
}
});
centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
centerPanel.setLayout(new GridLayout(0, 2, 5, 5));
centerPanel.add(nameLabel);
centerPanel.add(nameField);
centerPanel.add(addLabel);
centerPanel.add(addField);
centerPanel.add(occLabel);
centerPanel.add(occField);
centerPanel.add(phoneLabel);
centerPanel.add(phoneField);
footerPanel = new JPanel();
footerPanel.add(hideButton);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new InvisiblePanel().displayGUI();
}
});
}
}
You can do JFrame.invalidate() to refresh. Have a look at the link for more details. A similar requirement for a different question. refresh the contents of frame in real time