Cannot close frame using button after opening a new one in swing - java

package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class login extends javax.swing.JFrame implements ActionListener, javax.swing.RootPaneContainer {
private static final long serialVersionUID = 1L;
private JTextField TUserID=new JTextField(20);
private JPasswordField TPassword=new JPasswordField(20);
protected int role;
public JButton bLogin = new JButton("continue");
private JButton bCancel = new JButton("cancel");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new login().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel();
JLabel l2 = new JLabel("(2011)");
l2.setFont(new Font("Courier New", Font.BOLD, 10));
l.setIcon(icon);
JLabel LUserID=new JLabel("Your User ID: ");
JLabel LPassword=new JLabel("Your Password: ");
TUserID.addActionListener(this);
TPassword.addActionListener(this);
TUserID.setText("correct");
TPassword.setEchoChar('*');
TPassword.setText("correct");
bLogin.setOpaque(true);
bLogin.addActionListener(this);
bCancel.setOpaque(true);
bCancel.addActionListener(this);
JFrame f = new JFrame("continue");
f.setUndecorated(true);
f.setSize(460,300);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 80) / 100.0f);
Container pane = f.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS) );
pane.setBackground(Color.BLACK);
Box box0 = Box.createHorizontalBox();
box0.add(Box.createHorizontalGlue());
box0.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
box0.add(l);
box0.add(Box.createRigidArea(new Dimension(100, 0)));
pane.add(box0);
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box.add(Box.createRigidArea(new Dimension(100, 0)));
box.add(LUserID);
box.add(Box.createRigidArea(new Dimension(32, 0)));
box.add(TUserID);
LUserID.setMaximumSize( LUserID.getPreferredSize() );
TUserID.setMaximumSize( TUserID.getPreferredSize() );
pane.add(box);
Box box2 = Box.createHorizontalBox();
box2.add(Box.createHorizontalGlue());
box2.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box2.add(Box.createRigidArea(new Dimension(100, 0)));
box2.add(LPassword,LEFT_ALIGNMENT);
box2.add(Box.createRigidArea(new Dimension(15, 0)));
box2.add(TPassword,LEFT_ALIGNMENT);
LPassword.setMaximumSize( LPassword.getPreferredSize() );
TPassword.setMaximumSize( TPassword.getPreferredSize() );
pane.add(box2);
Box box3 = Box.createHorizontalBox();
box3.add(Box.createHorizontalGlue());
box3.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 100));
box3.add(bLogin);
box3.add(Box.createRigidArea(new Dimension(10, 0)));
box3.add(bCancel);
pane.add(box3);
f.setLocation(450,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
String TBUsername = TUserID.getText();
Object src = evt.getSource();
char[] CHPassword1 = TPassword.getPassword();
String TBPassword = String.valueOf(CHPassword1);
login mLogin = this;
if (src==bLogin) {
if (authenticate(TBUsername,TBPassword)) {
System.out.println(this);
exitApp(this);
} else {
exitApp(this);
}
} else if (src==bCancel) {
exitApp(mLogin);
}
}
public void exitApp(JFrame mlogin) {
mlogin.setVisible(false);
}
private boolean authenticate(String uname, String pword) {
if ((uname.matches("correct")) && (pword.matches("correct"))) {
new MyJFrame().createAndShowGUI();
return true;
}
return false;
}
}
and MyJFrame.java
package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MyJFrame extends javax.swing.JFrame implements ActionListener {
private static final long serialVersionUID = 2871032446905829035L;
private JButton bExit = new JButton("Exit (For test purposes)");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyJFrame().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JPanel p = new JPanel();
p.setBackground(Color.black);
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel("(2011)"); //up to here
l.setIcon(icon);
p.add(l);
p.add(bExit);
bExit.setOpaque(true);
bExit.addActionListener(this);
JFrame f = new JFrame("frame");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setUndecorated(true);
p.setOpaque(true);
f.getContentPane().add(p);
f.pack();
f.setSize(1000,600);
Container pane=f.getContentPane();
pane.setLayout(new GridLayout(0,1) );
//p.setPreferredSize(200,200);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 90) / 100.0f);
f.setLocation(300,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src==bExit) {
System.exit(0);
}
}
}
I cannot get the exitApp() method to work, although it worked before I expanded on my code, I've been trying for hours to get it to work but no avail! The login button suceeds in opening the new frame but will not close the preious(login) frame. It did earlier till I added the validation method etc ....

Create only one JFrame as parent and for another Top-level Containers create only once JDialog (put there JPanel as base), and re-use that for another Action, then you only to remove all JComponents from Base JPanel and add there another JPanel
don't forget for as last lines after switch betweens JPanels inside Base JPanel
revalidate();
repaint();
you can pretty to forgot about that by implements CardLayout

Related

Getting text from textfield does not work

Hello I found a Projekt on yt where you can search for a keyword and it will show all the websites it found on google. And right now I am trying to revive the keyword the user put in the textfield but it isn't working. It does not find the textfield (tf1) I made, but I don't know what I did wrong. Thanks in advance!
here's my code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Main implements ActionListener {
public static void main(String[] args) {
int frameWidth = 600;
int frameHeight = 600;
JFrame f = new JFrame();
JLabel l1 = new JLabel();
JTextField tf1 = new JTextField();
JButton b1 = new JButton();
f.getContentPane().setBackground(Color.PINK);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setSize(frameWidth, frameHeight);
f.setTitle("Search");
f.setLocationRelativeTo(null);
f.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
f.add(l1);
f.add(tf1);
f.add(b1);
l1.setText("Enter Keywords");
tf1.setPreferredSize(new Dimension(200, 20));
tf1.revalidate();
b1.setText("Search");
b1.addActionListener(new Main());
f.setVisible(true);
// ArrayList<WebCrawler> bots = new ArrayList<>();
// bots.add(new WebCrawler("", 1));
// bots.add(new WebCrawler("", 2));
// bots.add(new WebCrawler("", 3));
// for(WebCrawler w : bots) {
// try {
// w.getThread().join();
//
// }catch(InterruptedException e) {
// e.printStackTrace();
// }
// }
}
#Override
public void actionPerformed(ActionEvent e) {
String keyword = tf1.getText(); //Here it does not find the tf I made
System.out.println(keyword); //just for confirmation
}
}
You have a reference issue.
tf1 is declared as a local variable within main, which makes it inaccessible to any other method/context. Add into the fact that main is static and you run into another problem area.
The simple solution would be to make tf1 a instance field. This would be further simplified if you grouped your UI logic into a class, for example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label;
private JTextField textField;
private JButton searchButton;
public TestPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(Color.PINK);
setLayout(new GridBagLayout());
label = new JLabel("Enter Keywords: ");
textField = new JTextField(20);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(8, 8, 8, 8);
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
gbc.gridx++;
add(textField, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(searchButton, gbc);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
JOptionPane.showMessageDialog(TestPane.this, "You want to search for: " + text);
}
};
textField.addActionListener(listener);
searchButton.addActionListener(listener);
}
}
}
This is basic Java 101. You might find something like What is the difference between a local variable, an instance field, an input parameter, and a class field? of help

How do I update a JLabel during run time

the JLabel's name is set to an int which changes as the user modifies the number, i tried label.revalidate and Label.repaint after the user changes the int value. i have seen in similar questions people suggest creating a new jlabel everytime, but im wondering if there is a simpler way? the code is very long so i will summerize when needed.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class officia {
static JFrame Frame;
static JPanel Panel;
static JTextField healthPlace;
static String health="0";
static JButton begin;
static JLabel heart;
static int loop;
public static void main(String[] args) {
Panel = new JPanel();
Frame = new JFrame();
Frame.setSize(500,1000);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(Panel);
Panel.setLayout(null);
//adds panel and frame
healthPlace = new JTextField();
healthPlace.setBounds(170, 130, 165, 25);
Panel.add(healthPlace);
begin = new JButton("Begin");
begin.setBounds(217, 185, 70, 25);
Panel.add(begin);
while(loop==1)
loop=0;
heart = new JLabel(health);
heart.setBounds(150, -85, 500, 500);
Panel.add(heart);
Frame.setVisible(true);
//inputs gui's
ActionListener beginPressed = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
health = healthPlace.getText();
loop=1;
}
};
begin.addActionListener(beginPressed);
}
}
You're working in a event driven environment, that is, something happens and you respond to it.
This means, you're while-loop is ill-conceived and is probably the source of your issue. How can the ActionListener for the button be added when the loop is running, but you seem to using the ActionListener to exit the loop...
I modified you code slightly, so when you press the button, it will update the label.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class officia {
static JFrame Frame;
static JPanel Panel;
static JTextField healthPlace;
static String health = "0";
static JButton begin;
static JLabel heart;
static int loop;
public static void main(String[] args) {
Panel = new JPanel();
Frame = new JFrame();
Frame.setSize(500, 1000);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(Panel);
Panel.setLayout(null);
//adds panel and frame
healthPlace = new JTextField();
healthPlace.setBounds(170, 130, 165, 25);
Panel.add(healthPlace);
begin = new JButton("Begin");
begin.setBounds(217, 185, 70, 25);
Panel.add(begin);
// This is ... interesting, but a bad idea
// while (loop == 1) {
// loop = 0;
// }
heart = new JLabel(health);
heart.setBounds(150, -85, 500, 500);
Panel.add(heart);
Frame.setVisible(true);
//inputs gui's
ActionListener beginPressed = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
health = healthPlace.getText();
loop ++;
heart.setText(Integer.toString(loop));
}
};
begin.addActionListener(beginPressed);
}
}
JLabel#setText is what's known as a stateful property, that is, it will trigger an update that will cause it to be painted, so, if it's not updating, you're doing something wrong.
Possible runnable example (of what I think you want to do)
You're working a very rich UI framework. One if it's, many, features, is the layout management framework, something you should seriously take the time to learn to understand and use.
See Laying Out Components Within a Container for more details.
Below is a relatively simple example which shows one way you might "swicth" between views based on a response to a user input
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new BasePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BasePane extends JPanel {
private CardLayout cardLayout;
public BasePane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
StartPane startPane = new StartPane(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(BasePane.this, "HeartPane");
}
});
HeartPane heartPane = new HeartPane();
add(startPane, "StartPane");
add(heartPane, "HeartPane");
}
}
public class StartPane extends JPanel {
public StartPane(ActionListener actionListener) {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
JButton start = new JButton("Begin");
add(start);
start.addActionListener(actionListener);
}
}
public class HeartPane extends JPanel {
private JTextField heartTextField;
private JLabel heartLabel;
public HeartPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
heartLabel = new JLabel("Heart");
heartTextField = new JTextField(10);
add(heartLabel);
add(heartTextField);
}
}
}

Why can't I change the JButton (disabled) text color?

I started programming Java. This is my first window application. I did a simple tic-tac-toe game and I want the "o" button font color to be a different color. But it doesn't work. I can change the background color, but not the fonts, why?
package moje;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.print.PrinterJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JTextField;
public class Kolko_i_krzyzyk extends JFrame implements ActionListener {
static JTextField tekst;
static JLayeredPane ekran = new JLayeredPane();
static JButton button = new JButton();
static int licznik=0;
public Kolko_i_krzyzyk () {
super("Kółko i krzyżyk");
ekran = new JLayeredPane();
setVisible(true);
setSize(800, 800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Siatka podzielona 3 na 3
setLayout(new GridLayout(3,3));
//Tworzenie 9 przycisków
for(int i = 1; i<=9; i++) {
JButton button = new JButton();
add(button);
button.addActionListener(this);
}
}
public static void main(String[] args) {
JFrame okno = new Kolko_i_krzyzyk();
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if(licznik%2==0 ) {
button.setText("x");
button.setFont(new Font ("Arial", Font.BOLD, 90));
}
else {
button.setText("O");
button.setForeground(Color.RED);
button.setFont(new Font ("Arial", Font.BOLD, 90));
}
button.setEnabled(false);
licznik++;
}
}
The issue here is the default behavior when disabling the JButton via setEnabled(false).
This will grey out the button and ignore any color formatting you did to the text (foreground).
There are several workarounds to modify this behavior (as seen in this similar question).
Here is a short demonstration (without the final game logic of course) , which changes the UI of the JButton via setUI().
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.plaf.metal.MetalButtonUI;
public class Test {
private int counter = 0;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Test().buildGui());
}
private void buildGui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++) {
JButton button = new JButton() {
#Override
public Dimension getPreferredSize() {
return new Dimension(150, 150);
}
};
button.setFont(new Font("Arial", Font.BOLD, 90));
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (counter % 2 == 0) {
button.setText("X");
button.setUI(new MetalButtonUI() {
// override the disabled text color for the button UI
protected Color getDisabledTextColor() {
return Color.BLUE;
}
});
} else {
button.setText("O");
button.setUI(new MetalButtonUI() {
protected Color getDisabledTextColor() {
return Color.RED;
}
});
}
button.setEnabled(false);
counter++;
}
});
}
frame.pack();
frame.setVisible(true);
}
}
Result:
Another (simpler) way to do it would be to build some ImageIcons for "X" and "O", then set these on the buttons via setIcon()/setDisabledIcon(). This would save you the trouble from modifying the button UI.

Having a JTextField popup at a certain location after clicking a JButton

I have my three JButtons located where I want them (at the top center of the frame), and when the user clicks one, a JTextField pops up in the BoxLayout like wanted.
The problem is, when the JTextField shows up, it is to the left of the buttons, and it moves them.
I tried setting the alignment of the JTextField and using various glues, but the JTextField doesn't move.
If I want to have the JTextField pop up below my JButtons and in the center of the screen, what should I use?
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Library extends JFrame implements ActionListener {
private JFrame jf1;
private JPanel jp1;
private JTextField jtf1;
private JButton jb1;
private JButton jb2;
private JButton jb3;
public Library() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception q) {
q.printStackTrace();
}
JFrame.setDefaultLookAndFeelDecorated(false);
jf1 = new JFrame("Library");
jf1.setVisible(true);
jf1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf1.setSize(1080, 900);
jf1.setResizable(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
jf1.setLocation(dim.width/2-jf1.getSize().width/2, dim.height/2-jf1.getSize().height/2);
jp1 = (JPanel) jf1.getContentPane();
jp1.setLayout(new BoxLayout(jp1, BoxLayout.LINE_AXIS));
jb1 = new JButton("Genre");
jb1.addActionListener(this);
jb1.setMinimumSize(new Dimension(140, 60));
jb1.setPreferredSize(new Dimension(150, 60));
jb1.setMaximumSize(new Dimension(150, 60));
jb1.setAlignmentY(-70.0f);
jb2 = new JButton("Author");
jb2.addActionListener(this);
jb2.setMinimumSize(new Dimension(140, 60));
jb2.setPreferredSize(new Dimension(150, 60));
jb2.setMaximumSize(new Dimension(150, 60));
jb2.setAlignmentY(-70.0f);
jb3 = new JButton("Title");
jb3.addActionListener(this);
jb3.setMinimumSize(new Dimension(140, 60));
jb3.setPreferredSize(new Dimension(150, 60));
jb3.setMaximumSize(new Dimension(150, 60));
jb3.setAlignmentY(-70.0f);
jp1.add(Box.createHorizontalGlue());
jp1.add(jb1);
jp1.add(jb2);
jp1.add(jb3);
jp1.add(Box.createHorizontalGlue());
jf1.validate();
}
#Override
public void actionPerformed(ActionEvent e) {
Object code = e.getSource();
if (code == jb1) {
jtf1 = new JTextField("Enter Text");
jtf1.setPreferredSize(new Dimension(200,20));
jtf1.setMaximumSize(new Dimension(200,20));
jtf1.setMinimumSize(new Dimension(10,10));
jp1.add(jtf1);
jp1.validate();
}
else if (code == jb2) {
}
else if (code == jb3) {
}
}
public static void main(String[] args) {
Library shoe = new Library();
}
}
Suggestion: do not add/remove UI elements dynamically. Just add all of those things initially, and simply call setVisible(false) on your text field then.
(instead of adding/removing fields using your action listener)
A good and easy solution may be to use another JPanel to hold your dynamically created text fields. This may be what you wanted:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class Library extends JFrame implements ActionListener {
private JFrame jf1;
private JPanel jp1;
private JPanel jp2;
private JTextField jtf1;
private JButton jb1;
private JButton jb2;
private JButton jb3;
public Library() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception q) {
q.printStackTrace();
}
JFrame.setDefaultLookAndFeelDecorated(false);
jf1 = new JFrame("Library");
jf1.setVisible(true);
jf1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf1.setSize(1080, 900);
jf1.setResizable(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
jf1.setLocation(dim.width/2-jf1.getSize().width/2, dim.height/2-jf1.getSize().height/2);
jp1 = new JPanel();
jp1.setLayout(new BoxLayout(jp1, BoxLayout.LINE_AXIS));
jp2 = new JPanel();
jp2.setLayout(new BoxLayout(jp2, BoxLayout.LINE_AXIS));
jb1 = new JButton("Genre");
jb1.addActionListener(this);
jb1.setMinimumSize(new Dimension(140, 60));
jb1.setPreferredSize(new Dimension(150, 60));
jb1.setMaximumSize(new Dimension(150, 60));
jb1.setAlignmentY(-70.0f);
jb2 = new JButton("Author");
jb2.addActionListener(this);
jb2.setMinimumSize(new Dimension(140, 60));
jb2.setPreferredSize(new Dimension(150, 60));
jb2.setMaximumSize(new Dimension(150, 60));
jb2.setAlignmentY(-70.0f);
jb3 = new JButton("Title");
jb3.addActionListener(this);
jb3.setMinimumSize(new Dimension(140, 60));
jb3.setPreferredSize(new Dimension(150, 60));
jb3.setMaximumSize(new Dimension(150, 60));
jb3.setAlignmentY(-70.0f);
jp1.add(Box.createHorizontalGlue());
jp1.add(jb1);
jp1.add(jb2);
jp1.add(jb3);
jp1.add(Box.createHorizontalGlue());
jf1.getContentPane().add(jp1);
jp1.setBounds(0, 0, 1080, 900);
jf1.getContentPane().add(jp2);
jp2.setBounds(0, 0, 1080, 900);
validate();
}
public void actionPerformed(ActionEvent e) {
Object code = e.getSource();
if (code == jb1) {
jtf1 = new JTextField("Enter Text");
jtf1.setPreferredSize(new Dimension(200,20));
jtf1.setMaximumSize(new Dimension(200,20));
jtf1.setMinimumSize(new Dimension(10,10));
jp2.add(Box.createHorizontalGlue());
jp2.add(jtf1);
jp2.add(Box.createHorizontalGlue());
jp2.validate();
}
else if (code == jb2) {
}
else if (code == jb3) {
}
}
public static void main(String[] args) {
Library shoe = new Library();
}
}
I gave it a quick try to solve the issue. Hope it helps. Do more tweaking in your code to perfectly match the layout.

Dynamically adding textboxes and JSlider from a different class

I want to add textfields dynamically on the click of a button but the value to be fetched and the button are in one class and the panel where i want to add the textboxes and sliders adjacent to the are in a different class. Code is -
public class TipSplitting extends JPanel
JLabel lblNoOfGuests = new JLabel("No. Of guests");
lblNoOfGuests.setBounds(10, 26, 95, 14);
add(lblNoOfGuests);
private JTextField noofguests = new JTextField();
noofguests.setBounds(179, 23, 86, 20);
add(noofguests);
noofguests.setColumns(10);
JButton btnTiptailoring = new JButton("TipTailoring");
btnTiptailoring.setBounds(117, 286, 89, 23);
add(btnTiptailoring);
public class TipTailoring extends JPanel {}
In this class I need to create the text fields dynamically according to the no. entered. In the variable noofguests and the click of the button in the previous class.
I can't really see what the problem, but here some simple demo code of what you describe.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestDynamicallyAddedTextFields {
private void initUI() {
JFrame frame = new JFrame(TestDynamicallyAddedTextFields.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel textfieldContainerPanel = new JPanel();
textfieldContainerPanel.setLayout(new GridBagLayout());
JLabel nrOfGuests = new JLabel("Nr. of guests");
final JFormattedTextField textfield = new JFormattedTextField();
textfield.setValue(Integer.valueOf(1));
textfield.setColumns(10);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textfield.getValue() != null) {
addTextFieldsToPanel((Integer) textfield.getValue(), textfieldContainerPanel);
}
}
});
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING));
panel.add(nrOfGuests);
panel.add(textfield);
panel.add(add);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(textfieldContainerPanel));
frame.setSize(300, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected void addTextFieldsToPanel(Integer value, JPanel textfieldContainerPanel) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
for (int i = 0; i < value; i++) {
textfieldContainerPanel.add(new JTextField(20), gbc);
}
textfieldContainerPanel.revalidate();
textfieldContainerPanel.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestDynamicallyAddedTextFields().initUI();
}
});
}
}
And the result:

Categories

Resources