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
Related
I am trying to use a layered pane to make a menu for a program I'm working on, but the button won't display. I can't seem to figure out what it is...
public class FlashcardGUI {
public static void main(String[] args)
{
JFrame projectFrame = new JFrame("StudyFast Flashcard");
projectFrame.setName("StudyFast Flashcards");
projectFrame.setSize(1000,600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
projectFrame.setVisible(true);
JLayeredPane projectLayeredPane = new JLayeredPane();
projectFrame.setContentPane(projectLayeredPane);
JPanel projectMenu1 = new JPanel();
projectLayeredPane.setLayer(projectMenu1, 0);
final JButton startNow = new JButton();
startNow.setText("Exit");
startNow.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
projectFrame.add(projectLayeredPane);
projectLayeredPane.add(projectMenu1);
projectMenu1.add(startNow);
}
}
Put these two lines at the end of your main method. The order is important in order to make the button display.
projectFrame.pack();
projectFrame.setVisible(true);
(Make sure to remove the projectFrame.setVisible(true); you already have on line 9.)
I have updated your code and it is working now. Please see the inline comments for the issue in your code. Hope this helps.
public class FlashcardGUI2 {
public static void main(String[] args) {
JFrame projectFrame = new JFrame("StudyFast Flashcard");
projectFrame.setName("StudyFast Flashcards");
projectFrame.setSize(1000,600);
projectFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
projectFrame.setVisible(true);
JLayeredPane projectLayeredPane = new JLayeredPane();
LayoutManager layout = new FlowLayout(); //creating a FlowLayout object
projectLayeredPane.setLayout(layout); //adding the layout to JLayeredPane
//because JLayeredPane do not have default layout of
//its own. The reason you were not
//getting the button displayed
projectLayeredPane.setPreferredSize(new Dimension(300, 310));
JPanel projectMenu1 = new JPanel();
final JButton startNow = new JButton();
startNow.setText("Exit");
startNow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
projectLayeredPane.add(projectMenu1,new Integer(50));
projectLayeredPane.add(startNow,new Integer(10));
projectFrame.add(projectLayeredPane);
projectFrame.pack();
}
}
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++;
}
}
I used the NteBeans' GUI making tool.
It created a frame.
I want to close this frame using a button.
I know that I need to use "my_frame_name.dispose();" to close a frame.
But the problem is I cant find the name of the frame in the "Source" tab.
I think this is because, NetBeans created this frame and its code automatically.
Could anyone tell me how to close this frame using a code or a function, please?
Please don't tell me I have to recode everything, because I have multiple frames like tis one and don't have the luxury of time.
You can try this one also
Here program is using container.getParent() method to find out the top most JFrame.
public static void main(String[] a) {
JFrame frame = new JFrame();
JPanel p = new JPanel();
final JButton btn = new JButton("close");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Container parent = btn;
while ((parent = parent.getParent()) != null) {
System.out.println(parent.getClass().getName());
if (parent instanceof JFrame) {
((JFrame) parent).setVisible(false);
} else {
parent = parent.getParent();
}
}
}
});
p.add(btn);
frame.getContentPane().add(p);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
I am having an issue with my horizontal scroll bar demo. I am trying to move a custom message panel using the scroll bar. I used an anonymous listener and override the adjustmentValueChanged() method like so,
public void adjustmentValueChanged(AdjustmentEvent e){
System.out.println(e.getAdjustmentType());
if( e.getAdjustmentType() == AdjustmentEvent.UNIT_INCREMENT ) {
panel.moveLeft();
}
}
I am trying to get the AdjustmentEvent using e.getAdjustmentType() so I can properly handle the adjustment of the message panel. However, it is not working. I used System.out.println() method to print the adjustment type on my screen to see what the problem is but what I am not understanding is that no matter what part of the scroll bar I press (whether it is the unit increment, unit decrement, block increment, etc..) the value returned is 5? I am not sure what the issue is can someone please help.
public class ScrollBarDemo extends JFrame {
private JScrollBar scrollHort = new JScrollBar(JScrollBar.HORIZONTAL);
private JScrollBar scrollVert = new JScrollBar(JScrollBar.VERTICAL);
private MessagePanel panel = new MessagePanel("Welcom to Java bitch");
public static void main(String[] args) {
ScrollBarDemo frame = new ScrollBarDemo();
frame.setTitle("ScrollBarDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public ScrollBarDemo() {
setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);
add(scrollHort, BorderLayout.SOUTH);
add(scrollVert, BorderLayout.EAST);
scrollHort.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println(e.getAdjustmentType());
if (e.getAdjustmentType() == AdjustmentEvent.UNIT_INCREMENT) {
panel.moveLeft();
}
}
});
}
}
Run the following sample, the method to use is getValue().
public class ScrollBarDemo extends JFrame {
public ScrollBarDemo() {
setLayout( new BorderLayout());
final JScrollBar scrollHort = new JScrollBar( JScrollBar.HORIZONTAL );
add( scrollHort, BorderLayout.SOUTH );
scrollHort.addAdjustmentListener( e -> System.out.println( e.getValue()));
setLocationRelativeTo(null);
setDefaultCloseOperation( EXIT_ON_CLOSE );
pack();
setVisible(true);
}
public static void main( String[] args ) {
new ScrollBarDemo();
}
}
I already have a pretty basic Java Swing program but realised that I could do with a simple Username/password login screen to restrict access to it to only people with the username and password.
Is there anyway that I can insert some code to the start of the main method which will prevent execution beyond it until the username and password are entered on a screen that appears?
Here is an example of a Login Dialog. Closes entire program with close of Dialog.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("stackoverflow".equals(String.valueOf(jpfPassword.getPassword()))
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
This is very tricky to do (as you probably realize), to ensure that someone can't sidestep your authentication.
If you don't care too much if someone can get past it, then an easy way to accomplish what you're trying would be to create a variable tracking login process and don't allow your main thread to start the GUI thread of the main application until the authentication is completed. Something like this would work:
public class MyApp {
private static boolean isAuthenticated;
public static void main( String args[] ) {
isAuthenticated = false;
while( !isAuthenicated ) {
authenticateUser();
try{ Thread.sleep( 200 ); } catch( InterruptedException ie ){ }
}
new JFrame();
// finish rest of GUI code.
}
private static void authenticateUser(){
dialog = new MyAuthenticationDialog();
dialog.show();
if( isValid( dialog.getUsername(), dialog.getPassword() )
isAuthenticated = true;
else
isAuthenticated = false;
}
}
If you care whether this can be reverse engineered however (this example would be trivial for me to RE), then you will need to have some encrypted value that uses the correct username and password as a key. Hash these together into a SHA-256 key and encrypt the value. Note that an RE could still bypass this but it will take more effort, especially if you repeatedly check that you can decrypt the value with the user provided credentials in random spots all through your code. Don't use a single function for it otherwise the RE need only patch that one function and his job is easy. At the end of the day you don't have control over the client so no solution will be perfect. These are some ideas. Also run your final code through a Java obfuscator.
You can use a DialogBox with Swing as soon as you execute your main method. Then, based on the code, you can validate. If the values entered are ok with the authentication data (incoming from db, files, etc), then you show your main UI, if not, maybe you can show a dialog with something like "Try again" or close the dialog.
http://java.about.com/od/UsingDialogBoxes/a/How-To-Make-A-Password-Dialog-Box.htm
Hope it helps, best regards.