Adding components one after another to JPanel horizontally [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having problems with the components alignment added to JPanel. I am working on a chat application. Which layout should be used be used to get the intended aim. I tried all the layouts but I didn't get the wants. Mostly problems occur when window is resized. Moreover get the idea from the included image about what I want to be achieved.
Thanks in advance.
enter image description here

I whipped up a prototype using BoxLayout, for no other reason than I rarely use it and felt like trying it. Normally, GridBagLayout would be my first choice for this.
EDIT: Added a pic (thanks trashgod!)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MessageAppDemo implements Runnable
{
private String[] messages = new String[] {
"Hello?",
"Hey, what's up?",
"Where are you?",
"Right behind you.",
"Stop following me!",
"But you owe me money.",
"I'll gladly repay you on Tuesday.",
"You said that last week!",
"But now I actually have a job."
};
private int msgCounter = 0;
private JPanel panel;
private JScrollPane scrollPane;
private Timer timer;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new MessageAppDemo());
}
public void run()
{
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
scrollPane = new JScrollPane(panel);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(true);
JFrame frame = new JFrame("Message App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(260, 180);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
timer = new Timer(1500, new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (msgCounter < messages.length)
{
addMessage(messages[msgCounter]);
}
else
{
timer.stop();
}
}
});
timer.start();
}
private void addMessage(String text)
{
boolean rightAligned = msgCounter % 2 != 0;
Color color = rightAligned ? Color.CYAN : Color.ORANGE;
JLabel label = new JLabel(text);
label.setOpaque(true);
label.setBackground(color);
label.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.BLUE),
BorderFactory.createEmptyBorder(2,4,2,4)
));
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setBorder(BorderFactory.createEmptyBorder(2,4,2,4));
if (rightAligned)
{
p.add(Box.createHorizontalGlue());
p.add(label);
}
else
{
p.add(label);
p.add(Box.createHorizontalGlue());
}
panel.add(p);
panel.revalidate();
int x = panel.getPreferredSize().width;
int y = panel.getPreferredSize().height;
panel.scrollRectToVisible(new Rectangle(x-1 ,y-1, 1, 1));
msgCounter++;
}
}

Related

JAVA: Adding new buttons to a scrollable panel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am building a simple game and I need a grid with buttons of various colors. The grid should be 10 buttons in width and unbounded in height. There is an extra button at the bottom, which clones the already existing buttons onto the same grid. I need to keeps the sizes of the buttons the same as well as for a scroll bar to appear when adding too many buttons.
Some visuals of my problem can be found here.
I tried using a JScrollPane and I put the main JPanel inside of it, but the scroll bar doesn't appear. I am quite new at this, so any tips on how to deal with this would be much appreciated
My code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Main {
private JFrame window;
private JPanel mainPanel;
private JPanel currentButtonsPanel;
private ArrayList<JButton> buttons;
private final int WINDOW_X, WINDOW_Y;
private final int N_BUTTONS = 10;
private final Color[] colors = new Color[]{
Color.RED, Color.GREEN, Color.BLUE,
Color.YELLOW, Color.ORANGE, Color.MAGENTA};
private final Random random = new Random();
private JButton selectedButton = null;
public Main(int w, int h, String title){
WINDOW_X = w;
WINDOW_Y = h;
window = new JFrame(title);
window.setLayout(new BorderLayout());
window.setSize(new Dimension(w, h));
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
//mainPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
buttons = new ArrayList<>();
for(int i = 0; i < N_BUTTONS*3.5; i++)
addNewButton();
JScrollPane scrollPane = new JScrollPane(mainPanel);
scrollPane.setPreferredSize(new Dimension(w,h));
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
window.add(scrollPane, BorderLayout.CENTER);
window.add(generateButtonsPanel(), BorderLayout.SOUTH);
window.pack();
window.setVisible(true);
}
private JPanel generateButtonsPanel(){
JPanel ret = new JPanel();
JButton btn = new JButton("Check");
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
copyButtons();
}
});
ret.add(btn);
return ret;
}
private void copyButtons(){
ArrayList<JButton> newList = new ArrayList<>();
for(JButton btn : buttons){
JButton newBtn = new JButton();
newBtn.setBackground(btn.getBackground());
newBtn.addActionListener(btn.getActionListeners()[0]);
newList.add(newBtn);
}
for(JButton btn : newList)
addNewButton(btn);
}
private void addNewButton(){
JButton newButton = new JButton();
Color col = colors[random.nextInt(colors.length)];
newButton.setBackground(col);
newButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JButton btn = (JButton)e.getSource();
if(selectedButton == null){
selectedButton = btn;
btn.setText(".");
return;
}
if(selectedButton == btn){
selectedButton = null;
btn.setText("");
return;
}
if(selectedButton.getBackground() == btn.getBackground()){
System.out.println("Matching!");
btn.setBackground(Color.BLACK);
selectedButton.setBackground(Color.BLACK);
btn.setEnabled(false);
selectedButton.setEnabled(false);
buttons.remove(btn);
buttons.remove(selectedButton);
}else
System.out.println("No match!");
btn.setText("");
selectedButton.setText("");
selectedButton = null;
}
});
addNewButton(newButton);
}
private void addNewButton(JButton btn){
if(buttons.size() % 10 == 0){
currentButtonsPanel = new JPanel();
currentButtonsPanel.setLayout(new GridLayout(0,10));
currentButtonsPanel.setMaximumSize(new Dimension(WINDOW_X*WINDOW_X,WINDOW_X/N_BUTTONS+10));
currentButtonsPanel.add(btn);
mainPanel.add(currentButtonsPanel);
}else
currentButtonsPanel.add(btn);
buttons.add(btn);
window.setVisible(true);
}
public static void main(String[] args){
new Main(400, 300, "Game");
}
}
EDIT: This code is only experimental, so far I'm only interested in the technical aspects of this program, so everything is simplified.
I believe your problem is with currentButtonsPanel.setMaximumSize(new Dimension(WINDOW_X*WINDOW_X,WINDOW_X/N_BUTTONS+10));. The purpose of that method is to indicate to the Layout Manager the maximum size that the particular component will ever be, rather than telling it to set to that size. They layout manager has automatically determined what size your JPanel should be (as well as the buttons inside), and is following through with that determination in order to avoid using the scroll bar, all the while (correctly) obeying the Max size directive you gave it.
Try setPreferredSize() instead; this tells your Layout Manager the size that your component wants to be. This will cause the Layout Manager to set the JPanel to your preferred size, which should cause a vertical scrollbar to appear, given that you have a vertical scrolling policy set up.

Java - updating values in JFrame/JLabels

I am a beginner Java-coder and a few days ago I felt confident enough in my skills to start my first "big" project. It was basically a calculator, a GUI(only JFrame, JPanels, JLabels and Buttons) that would display data, accept user input, grab some more data from other classes, then calculate stuff and finally update the GUI with the new JLabel values. However I never managed to get the update part done properly, whenever I would press the 'process'-button it would create a new JFrame with the new values, while the old one was still up.
I tried the obvious stuff (repaint(), revalidate(), etc) but that didn't work at all, then I started to shift things around, put parts of the code into new classes, copied code from the net until it eventually worked. However the code was a total mess and I didn't even really understand what went exactly wrong in the first place, so I trashed the entire thing.
Here is a very simplified version of my code before things went downhill:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test_1 extends JFrame {
public static class clicks{
static int clicks = 0;
public int getclicks(){
return clicks;
}
public void setclicks(){
clicks = clicks+1;
}
}
public Test_1(){
clicks getNumber = new clicks();
int x = getNumber.getclicks();
//FRAME AND LAYOUT
JFrame window = new JFrame();
window.getContentPane().setBackground(Color.darkGray);
window.getContentPane().setLayout(new BorderLayout(20,10));
window.setTitle("Test Frame 1");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(true);
// Top JPanel
JPanel northpanel = new JPanel();
LayoutManager northlayout = new FlowLayout();
northpanel.setLayout(northlayout);
// Top JPanel content
JLabel nlabel1 = new JLabel("Hello North");
nlabel1.setPreferredSize(new Dimension(100,20));
northpanel.add(nlabel1);
JPanel westpanel = new JPanel();
LayoutManager westlayout = new BoxLayout(westpanel, BoxLayout.Y_AXIS);
westpanel.setLayout(westlayout);
JLabel wlabel1 = new JLabel("Hello West");
wlabel1.setPreferredSize(new Dimension(100,20));
westpanel.add(wlabel1);
JPanel eastpanel = new JPanel();
LayoutManager eastlayout = new BoxLayout(eastpanel, BoxLayout.Y_AXIS);
eastpanel.setLayout(eastlayout);
JLabel elabel1 = new JLabel ("Hello East");
elabel1.setPreferredSize(new Dimension(100,20));
eastpanel.add(elabel1);
JButton southbutton = new JButton("start");
southbutton.setPreferredSize(new Dimension(400,50));
southbutton.addActionListener(new Action());
JPanel centralpanel = new JPanel();
JLabel clabel1 = new JLabel("Clicks: " + x);
centralpanel.add(clabel1);
window.add(centralpanel, BorderLayout.CENTER);
window.add(southbutton, BorderLayout.SOUTH);
window.add(eastpanel, BorderLayout.EAST);
window.add(westpanel, BorderLayout.WEST);
window.add(northpanel, BorderLayout.NORTH);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
Test_1 window_start = new Test_1();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e){
clicks Numbers = new clicks();
Numbers.setclicks();
int test = Numbers.getclicks();
System.out.println("Button works, Number of clicks: "+test);
Test_1 updateData = new Test_1();
}
}
}
I know that the ActionListener creates a new instance of my JFrame, however that was the closest I ever came to "updating the JFrame" before I turned the code into Spaghetti. I assume that the way I build my code is the cause of my problem but creating the Frame and its content it different classes didn't work at all.
So my questions are:
Is there something really obvious I missing? Would it be possible to make this run the way I want to without completely changing it?
Is there a more efficient way to create a GUI? I get the feeling that the way I made this is total garbage.
I read other questions that dealt with similar problems but maybe it's because I am still pretty bad at Java but I couldn't really tell if they were related to my problem. Also I really want to understand this, so copying someone elses code wouldn't help at all.
Any help or comments are appreciated.
btw, the class click is something I just put there as a placeholder.
Alrighty I managed to get it to work. It's probably against the Etiquette to answer to his own question but I thought it might be useful for some beginners(like me yesterday). So here is my new code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test_1 extends JFrame {
public static class clicks{
static int clicks = 0;
public int getclicks(){
return clicks;
}
public void setclicks(){
clicks = clicks+1;
}
}
clicks getNumber = new clicks();
int x = getNumber.getclicks();
JPanel northpanel, westpanel, eastpanel, southpanel, centralpanel;
static JLabel nlabel1, nlabel2, nlabel3, nlabel4, nlabel5;
static JLabel wlabel1, wlabel2, wlabel3, wlabel4, wlabel5;
static JLabel elabel1, elabel2, elabel3, elabel4, elabel5;
static JLabel clabel1;
JButton southbutton;
String TextnL, TextwL, TexteL;
public Test_1(){
setBackground(Color.darkGray);
setLayout(new BorderLayout(20,10));
setTitle("Test Frame 1");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
nlabel1 = new JLabel("North_1");
nlabel2 = new JLabel("North_2");
nlabel3 = new JLabel("North_3");
nlabel4 = new JLabel("North_4");
nlabel5 = new JLabel("North_5");
wlabel1 = new JLabel("West_1 ");
wlabel2 = new JLabel("West_2 ");
wlabel3 = new JLabel("West_3 ");
wlabel4 = new JLabel("West_4 ");
wlabel5 = new JLabel("West_5 ");
elabel1 = new JLabel("East_1");
elabel2 = new JLabel("East_2");
elabel3 = new JLabel("East_3");
elabel4 = new JLabel("East_4");
elabel5 = new JLabel("East_5");
clabel1 = new JLabel("START");
southbutton = new JButton("Process");
southbutton.addActionListener(new Action());
northpanel = new JPanel();
northpanel.add(nlabel1);
northpanel.add(nlabel2);
northpanel.add(nlabel3);
northpanel.add(nlabel4);
northpanel.add(nlabel5);
add(northpanel, BorderLayout.NORTH);
westpanel = new JPanel();
LayoutManager wBox = new BoxLayout(westpanel, BoxLayout.Y_AXIS);
westpanel.setLayout(wBox);
westpanel.add(wlabel1);
westpanel.add(wlabel2);
westpanel.add(wlabel3);
westpanel.add(wlabel4);
westpanel.add(wlabel5);
add(westpanel, BorderLayout.WEST);
eastpanel = new JPanel();
LayoutManager eBox = new BoxLayout(eastpanel, BoxLayout.Y_AXIS);
eastpanel.setLayout(eBox);
eastpanel.add(elabel1);
eastpanel.add(elabel2);
eastpanel.add(elabel3);
eastpanel.add(elabel4);
eastpanel.add(elabel5);
add(eastpanel, BorderLayout.EAST);
centralpanel = new JPanel();
centralpanel.add(clabel1);
add(centralpanel, BorderLayout.CENTER);
add(southbutton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
Test_1 window_start = new Test_1();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e){
clicks Numbers = new clicks();
Numbers.setclicks();
int test = Numbers.getclicks();
clabel1.setText("clicks: "+test);
}
}
}
And again, any comments/suggestions are welcome.

Centering components and resizing JFrame in swing

I am making a java GUI in which I have some vertical boxes. Inside those boxes, there are some buttons and Labels. I am trying to put the buttons and labels in the center but doesn't work!
I am using this code to set the label in the center.
JLabel update = new JLabel("update");
update.setHorizontalTextPosition(CENTER);
where update is the last component of my vertical box.
The other problem is that I need the window to resize automatically depending on the changes in my GUI (since it is a dynamic one)!
How can I make this too?
I am trying to put the buttons and labels in the center but doesn't work! I am using this code to set the label in the center.
There are several ways to do this, but the easiest for me is to use a GridBagLayout.
If the boxes/container (which hopefully extend from JPanel or JComponent) uses a GridBagLayout, and you add components into the container with GridBagConstraints: gridX and gridY set, but with weightX and weightY set to default of 0, those added components will center in the container.
I can't show code since I have no knowledge of the code you're currently using or the images of your observed/desired GUI's. If you need more help, please edit your question and provide more pertinent information.
The other problem is that I need the window to resize automatically depending on the changes in my GUI (since it is a dynamic one)! How can I make this too?
This will all depend on the layout managers that your GUI is using, something that we have no knowledge of as yet. Again, if you're still stuck, please create and post your Minimal, Complete, and Verifiable Example Program.
For example the following resizable GUI with centered buttons and JLabel texts:
Is created by the following code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class VertBoxes extends JPanel {
private static final String[] LABEL_TEXTS = { "A", "One", "Two", "Monday",
"Tuesday", "January", "Fourth of July",
"Four score and seven years ago" };
public static final int PREF_W = 260;
public static final int PREF_H = 80;
public VertBoxes() {
setLayout(new GridLayout(0, 1, 5, 5));
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
for (String labelTxt : LABEL_TEXTS) {
add(new InnerBox(labelTxt));
}
}
private class InnerBox extends JPanel {
public InnerBox(String labelTxt) {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createLineBorder(Color.black, 4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new JButton("Button"), gbc);
gbc.gridy++;
add(new JLabel(labelTxt), gbc);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
private static void createAndShowGui() {
VertBoxes mainPanel = new VertBoxes();
JFrame frame = new JFrame("Vertical Boxes");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

java create custom jpanel and use as a template [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
i want to create java component looks like my picture, because i'm gonna use it manytimes in my application .my idea is add a jpanel[left panel] and a Jlable [right lable] to a jpanel[main panel]. Main panel is the final object which i want to use again and again.
so my first step is create a main panel.and try to use it as a template.but i realized it's not work as i expected .this is my template class this is the class which i going to use again and again.
/////////////////////////////////////////
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
class customCompo extends JPanel {
void customCompoMeth() {
JPanel green = new JPanel();
green.setPreferredSize(new Dimension(80, 150));
green.setBackground(Color.GREEN);
}
}
//////////////////////////////////////////////
i have a another class which consist main method.here it is.how i use my above template again and again.
////////////////////////////////////////////////////////////////////
customCompo c1=new customCompo();
jPanel1.add(c1);
///////////////////////////////////////////////////////////////////
what i'm doing here is create new instance and add it to a component in this case Jpanel1.but it's not working .it gives me errors .i need a help what's my wrong ?am i completely wrong?
If I am able to understand the question in the correct way now, you simply wanted to create one JPanel with some added thingies to it, that one can reuse again and again, without writing the whole code. If that be the case, one simply needs to extend the JPanel and simply put the modifications one needs and reuse it, whereever needed, as already said by #peeskillet.
Do see this code example, and see if this is what you referring to:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ExampleTemplate {
private static final int GAP = 5;
private void displayGUI() {
JFrame frame = new JFrame("Swing Worker Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1, GAP, GAP));
contentPane.setBorder(new EmptyBorder(GAP, GAP, GAP, GAP));
contentPane.add(new TemplatePanel());
contentPane.add(new TemplatePanel());
contentPane.add(new TemplatePanel());
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ExampleTemplate().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class TemplatePanel extends JPanel {
private Random r;
private JPanel leftPanel;
private static final int GAP = 5;
private GridBagConstraints gbc;
public TemplatePanel() {
r = new Random();
setOpaque(true);
setBackground(getRandomColor());
setLayout(new BorderLayout(GAP, GAP));
JPanel footerPanel = getPanel();
footerPanel.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.8;
gbc.weighty = 1.0;
leftPanel = getPanel();
footerPanel.add(leftPanel, gbc);
gbc.gridx = 1;
gbc.weightx = 0.2;
JLabel rightLabel = new JLabel("Right Label", JLabel.CENTER);
footerPanel.add(rightLabel);
JLabel centerLabel = new JLabel("Main Panel", JLabel.CENTER);
add(centerLabel, BorderLayout.CENTER);
add(footerPanel, BorderLayout.PAGE_END);
}
private JPanel getPanel() {
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(getRandomColor());
return panel;
}
private Color getRandomColor() {
return new Color(r.nextFloat(), r.nextFloat(),
r.nextFloat(), r.nextFloat());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
}
"but it's not working .it gives me errors"
The first error I see in that little bit of code you provided, is the fact that you are trying to add an instance of a non-component class to a JPanel. That will fail. You should make the class extend JComponent, JPanel, or any other JComponent, if you want to add it to another panel.
See Creating GUI with Swing. You may need to get up to speed on the basics :)

How can I refresh or reload the JFrame? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am doing project using Java and in that I need to reload whole JFrame after clicking particular button on that JFrame. How to do this?
Try
SwingUtilities.updateComponentTreeUI(frame);
If it still doesn't work then after completing the above step try
frame.invalidate();
frame.validate();
frame.repaint();
just use
frame.setVisible(false);
frame.setVisible(true);
I've had this problem with JLabels with images, and this solved it
Here's a short code that might help.
<yourJFrameName> main = new <yourJFrameName>();
main.setVisible(true);
this.dispose();
where...
main.setVisible(true);
will run the JFrame again.
this.dispose();
will terminate the running window.
Try this code. I also faced the same problem, but some how I solved it.
public class KitchenUserInterface {
private JFrame frame;
private JPanel main_panel, northpanel , southpanel;
private JLabel label;
private JButton nextOrder;
private JList list;
private static KitchenUserInterface kitchenRunner ;
public void setList(String[] order){
kitchenRunner.frame.dispose();
kitchenRunner.frame.setVisible(false);
kitchenRunner= new KitchenUserInterface(order);
}
public KitchenUserInterface getInstance() {
if(kitchenRunner == null) {
synchronized(KitchenUserInterface.class) {
if(kitchenRunner == null) {
kitchenRunner = new KitchenUserInterface();
}
}
}
return this.kitchenRunner;
}
private KitchenUserInterface() {
frame = new JFrame("Lullaby's Kitchen");
main_panel = new JPanel();
main_panel.setLayout(new BorderLayout());
frame.setContentPane(main_panel);
northpanel = new JPanel();
northpanel.setLayout(new FlowLayout());
label = new JLabel("Kitchen");
northpanel.add(label);
main_panel.add(northpanel , BorderLayout.NORTH);
frame.setSize(500 , 500 );
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private KitchenUserInterface (String[] order){
this();
list = new JList<String>(order);
main_panel.add(list , BorderLayout.CENTER);
southpanel = new JPanel();
southpanel.setLayout(new FlowLayout());
nextOrder = new JButton("Next Order Set");
nextOrder.addActionListener(new OrderUpListener(list));
southpanel.add(nextOrder);
main_panel.add(southpanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
KitchenUserInterface dat = kitchenRunner.getInstance();
try{
Thread.sleep(1500);
System.out.println("Ready");
dat.setList(OrderArray.getInstance().getOrders());
}
catch(Exception event) {
System.out.println("Error sleep");
System.out.println(event);
}
}
}
You should use this code
this.setVisible(false); //this will close frame i.e. NewJFrame
new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed

Categories

Resources