Getting text from textfield does not work - java

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

Related

How do I check if the JFrame is fullscreen?

I'm trying to code an app using JFrame. But I have encountered an issue when trying to check if the window is full screen or not. I want my button to be in the same position when it's full and half screen. Here's my code.
package App.Gui;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import App.Gui.Event.ExitEvent;
public class WindowSettings {
private final static ImageIcon imageIcon = new ImageIcon("C:\\Users\\zeesh\\FirstApp\\src\\image\\Untitled.png");
public static void setWindow() {
JFrame frame = new JFrame("Debug Configurations");
JPanel panel = new JPanel();
frame.getContentPane();
JButton button = new JButton("X");
Dimension size = button.getPreferredSize();
button.setBounds(1125, 20, 50, 50);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ExitEvent.exit();
}
});
panel.setLayout(null);
panel.add(button);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setIconImage(imageIcon.getImage());
frame.setSize(1200, 750);
frame.setVisible(true);
}
}
Make use of appropriate layouts, for example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
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.JPanel;
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 {
public TestPane() {
setLayout(new BorderLayout());
JButton button = new SquareButton("X");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
JPanel topPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 1;
gbc.insets = new Insets(20, 50, 20, 50);
topPane.add(button, gbc);
add(topPane, BorderLayout.NORTH);
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.add(new JLabel("Stuff goes here"));
add(contentPane);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 750);
}
}
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
int stringWidth = fm.stringWidth(getText());
int stringHeight = fm.getHeight();
int size = Math.max(stringHeight, stringWidth);
return new Dimension(size + 22, size + 22);
}
}
}
See Laying Out Components Within a Container for more details
But, wait, you want to overlap the button over the top of the content? Well, that's not that hard...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
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.JPanel;
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 {
public TestPane() {
setLayout(new GridBagLayout());
JButton button = new SquareButton("X");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.insets = new Insets(20, 50, 20, 50);
add(button, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.setBackground(Color.MAGENTA);
contentPane.add(new JLabel("Stuff goes here"));
add(contentPane, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 750);
}
}
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
int stringWidth = fm.stringWidth(getText());
int stringHeight = fm.getHeight();
int size = Math.max(stringHeight, stringWidth);
return new Dimension(size + 22, size + 22);
}
}
}

JLabel - Cutting Off The Top of Image

in my new Java project I have a JFrame in which there is a JLabel set to North with BorderLayout, and below it is an image. The image fits fine on the JFrame, but the JLabel cuts off the top of it. How can I resize this JLabel? I tried setPreferredSize and that didn't work. Help would be appreciated.
Code:
package counter.main;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class FoodCounter {
public static JLabel greet4 = new JLabel("",SwingConstants.CENTER);
public static JLabel message4 = new JLabel();
public static JLabel lclicks4 = new JLabel();
public static JButton buttonClick4 = new JButton("+ Food");
public static int clicks4 = 0;
public static URL food = Main.class.getResource("/counter/main/FoodEating.wav");
public static JButton back = new JButton("Back");
public static JLabel bread;
static JFrame frame = new JFrame("Food Counter"); {
createView();
frame.setSize(500, 100);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.revalidate();
frame.repaint();
}
private void createView() {
final JPanel panelc = new JPanel();
frame.getContentPane().add(panelc);
panelc.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 11));
greet4.setFont(new Font( "Dialog", Font.PLAIN, 18));
greet4.setPreferredSize(new Dimension(40, 20));
panelc.add(message4);
frame.add(back, BorderLayout.WEST);
frame.add(greet4, BorderLayout.NORTH);
back.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
SelectionFrame.frame1.setVisible(true);
}
});
panelc.add(buttonClick4);
panelc.add(lclicks4);
updateCounter();
bread = new JLabel("");
bread.setPreferredSize(new Dimension(64, 64));
Image img = new ImageIcon(this.getClass().getResource("/counter/main/SlicedBread64.png")).getImage();
bread.setIcon(new ImageIcon(img));
frame.getContentPane().add(bread, BorderLayout.EAST);
buttonClick4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clicks4++;
updateCounter();
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(food);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException x) {
x.printStackTrace();
}
}
});
};
private void updateCounter() {
lclicks4.setText(clicks4 + "/100 Food ");
if (clicks4 < 1) {
message4.setText("Click to Begin! -->");
}
if (clicks4 >= 1 && clicks4 < 10) {
message4.setText("Keep Going!");
}
if (clicks4 >= 10 && clicks4 < 50) {
message4.setText("Keep 'em Comin'!");
}
if (clicks4 >= 50 && clicks4 < 70) {
message4.setText("Don't Stop!");
}
if (clicks4 >= 70 && clicks4 < 80) {
message4.setText("Almost!");
}
if (clicks4 >= 90 && clicks4 < 100) {
message4.setText("Finish Strong!");
}
if (clicks4 >= 100) {
try {
Thread.sleep(3000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.exit(0);
}
}
}
Don't set sizes, preferred sizes or similar issues on components and top-level windows if it can be avoided.
Instead let the GUI size itself by using layout managers smartly and by calling pack() on the top-level window after adding all components and before calling setVisible(true).
Consider putting dummy text into your greet4 JLabel, so that it takes up space when the GUI is packed. Some spaces, " " will likely suffice.
Unrelated recommendations:
Most of your variables should be instance variables, not static variables. Java is structured along object-oriented programming principles for many reasons, but a chief one is to reduce connections and its associated complexity. By using static variables and methods, you remove this benefit and risk creating programs with a high degree of cyclomatic complexity, making debugging difficult.
Likewise for variables declared as public. Prefer to use private fields to help reduce coupling and increase cohesion.
Run long-running code, such as the code that plays your music, in a background thread to avoid tying up the Swing event thread.
Never call Thread.sleep(...) within the Swing Event Dispatch Thread, or EDT, as this will put your entire Swing GUI to sleep.
For example,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class FoodCounter2 extends JPanel {
public static final String IMAGE_PATH = "https://duke.kenai.com/iconSized/duke.gif";
private static final Font TITLE_FONT = new Font("Dialog", Font.PLAIN, 18);
private JLabel titleLabel = new JLabel("Welcome, User", SwingConstants.CENTER);
private JButton backButton = new JButton("Back");
private JButton addFoodButton = new JButton("+ Food");
private JLabel foodCountLabel = new JLabel("0/100 Food");
public FoodCounter2() throws IOException {
URL imgUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imgUrl);
ImageIcon icon = new ImageIcon(img);
JPanel foodPanel = new JPanel(new GridBagLayout());
// JPanel foodPanel = new JPanel();
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10, 10, 10, 10);
foodPanel.add(new JLabel("Click to Begin! --->"), gbc);
gbc.gridx++;
foodPanel.add(addFoodButton, gbc);
gbc.gridx++;
foodPanel.add(foodCountLabel, gbc);
JPanel centerPanel = new JPanel(new BorderLayout());
titleLabel.setFont(TITLE_FONT);
centerPanel.add(titleLabel, BorderLayout.PAGE_START);
centerPanel.add(foodPanel, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(backButton, BorderLayout.LINE_START);
add(centerPanel, BorderLayout.CENTER);
add(new JLabel(icon), BorderLayout.LINE_END);
}
private static void createAndShowGui() {
FoodCounter2 mainPanel = null;
try {
mainPanel = new FoodCounter2();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("FoodCounter2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which displays as:
This is what is happening:
As you can see, the top part of the bread is cut off. This is because the JPanel is covering it I assume.

UTF-8 support issue to Java Swing? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
how to implement UTF-8 format in Swing application?
In Swing application I have the send button, one text area and a text field.
If I press the send button, I need to send the text from text field to text area
It's working fine in English But not in the local language...
package package1;
import java.awt.*;
import java.awt.event.*;
import java.io.UnsupportedEncodingException;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
class AEvent extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JTextField tf;
JTextArea area ;
Border border;
AEvent(){
area = new JTextArea(200,200);
area.setBounds(60,200,300,200);
border = BorderFactory.createLineBorder(Color.BLACK);
area.setBorder(border);
tf=new JTextField();
tf.setBounds(60,70,150,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);
add(tf);
add(area);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setSize(600,600);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
String s = null;
try {
s = new String(tf.getText().getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
area.setText(s);
}
public static void main(String args[]){
new AEvent();
}
}
Please give some Idea or some code that will help me to solve this..
This breaks if the the platform default encoding is not utf-8. tf.getText().getBytes() gives you the bytes in the platform default encoding. new String(tf.getText().getBytes(), "UTF-8") will create a corrupt string if the actual encoding of the bytes is not utf-8.
try
public void actionPerformed(ActionEvent e){
area.setText(tf.getText());
}
OK, so if you are still not convinced of Phillipe's answer, here is a fully working code which demonstrates the good answer. I tried it with accented characters and it works just fine. If it breaks, please indicate how.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
class AEvent implements ActionListener {
private JTextField tf;
private JTextArea area;
private JFrame frame;
protected void initUI() {
frame = new JFrame();
frame.setLayout(new GridBagLayout());
area = new JTextArea(30, 80);
area.setEditable(false);
area.setFocusable(false);
tf = new JTextField();
JButton b = new JButton("click me");
b.addActionListener(this);
JScrollPane scrollPane = new JScrollPane(area);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(scrollPane, gbc);
gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
frame.add(tf, gbc);
gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
frame.add(b, gbc);
frame.getRootPane().setDefaultButton(b);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
tf.requestFocusInWindow();
}
#Override
public void actionPerformed(ActionEvent e) {
area.append(tf.getText() + "\n");
tf.setText("");
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new AEvent().initUI();
}
});
}
}
Why this?
String s = null;
try {
s = new String(tf.getText().getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
area.setText(s);
Why not just:
area.setText(tf.getText());
I tried to do do your objective with a local language it worked fine for me. Can you please specify which local language are you considering and on what IDE are you working?

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:

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

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

Categories

Resources