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

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.

Related

JPanel gets compressed and disappears when trying to move to the bottom

I have to do a project in Java and thought a GUI Text Adventure would be cool. My Problem is that when I create a JPanel and move it further down on the screen, the panel first changes its size and then disappears completely at one point.
On the GameScreen there should be a panel for choice Options to be put on but it refuses to go further down than about half the size of the Screen.
Here's the code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
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.JTextArea;
public class Yeet {
JFrame epicOfYeet;
Container con;
JPanel titleNamePanel, startButtonPanel, mainTextPanel, choiceButtonPanel;
JLabel titleNameLabel;
Font titleFont = new Font("Times New Roman", Font.PLAIN, 90);
Font normalFont = new Font ("Times New Roman", Font.PLAIN, 55);
JButton startButton;
JButton choice1;
JButton choice2;
JButton choice3;
JButton choice4;
JTextArea mainTextArea;
TitleScreenHandler tsHandler = new TitleScreenHandler();
public static void main(String[] args) {
new Yeet();
}
public Yeet() {
epicOfYeet = new JFrame();
epicOfYeet.setSize(1200, 1000);
epicOfYeet.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
epicOfYeet.getContentPane().setBackground(Color.black);
epicOfYeet.setLayout(null);
con = epicOfYeet.getContentPane();
titleNamePanel = new JPanel();
titleNamePanel.setBounds(190, 100, 800, 230);
titleNamePanel.setBackground(Color.black);
titleNameLabel = new JLabel("EPIC OF YEET");
titleNameLabel.setForeground(Color.red);
titleNameLabel.setFont(titleFont);
startButtonPanel = new JPanel();
startButtonPanel.setBounds(400, 500, 400, 100);
startButtonPanel.setBackground(Color.black);
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
startButton.addActionListener(tsHandler);
startButton.setFocusPainted(false);
titleNamePanel.add(titleNameLabel);
startButtonPanel.add(startButton);
con.add(titleNamePanel);
con.add(startButtonPanel);
epicOfYeet.setVisible(true);
}
public void createGameScreen(){
titleNamePanel.setVisible(false);
startButtonPanel.setVisible(false);
mainTextPanel = new JPanel();
mainTextPanel.setBounds(100, 100, 1000, 400);
mainTextPanel.setBackground(Color.green);
con.add(mainTextPanel);
mainTextArea = new JTextArea("You come to your senses again.\nThe dewy grass you're laying on is gleaming with moonlight.\nYour body aches as you get up and catch a \nglimpse of your surroundings.\n");
mainTextArea.setBounds(100, 100, 1000, 250);
mainTextArea.setBackground(Color.blue);
mainTextArea.setForeground(Color.white);
mainTextArea.setFont(normalFont);
mainTextArea.setLineWrap(true);
mainTextPanel.add(mainTextArea);
choiceButtonPanel = new JPanel();
choiceButtonPanel.setBounds(300, 500, 600, 550);
choiceButtonPanel.setBackground(Color.red);
con.add(choiceButtonPanel);
}
public class TitleScreenHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
createGameScreen();
}
}
}
Here is a basic implementation using layout mangers, avoiding the bad practice of null layout manager.
It is not an optimal one, but should get you started:
import java.awt.BorderLayout;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Yeet {
JFrame epicOfYeet;
Container con;
JPanel titleNamePanel, startButtonPanel, mainTextPanel, choiceButtonPanel;
JLabel titleNameLabel;
Font titleFont = new Font("Times New Roman", Font.PLAIN, 90);
Font normalFont = new Font ("Times New Roman", Font.PLAIN, 55);
JButton startButton, coice1, choice2, choice3, choice4;
JTextArea mainTextArea;
TitleScreenHandler tsHandler = new TitleScreenHandler();
public static void main(String[] args) {
SwingUtilities.invokeLater(()->new Yeet());
}
public Yeet() {
epicOfYeet = new JFrame();
//epicOfYeet.setSize(1200, 1000); // do not set size. let layout manager calcualte it
epicOfYeet.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
epicOfYeet.getContentPane().setBackground(Color.black);
//epicOfYeet.setLayout(null); //aviod null layouts Jframe uses BorderLayout by default
con = epicOfYeet.getContentPane();
titleNamePanel = new JPanel();
//titleNamePanel.setBounds(190, 100, 800, 230);
titleNamePanel.setPreferredSize(new Dimension(800, 230));//set preferred size to be used by layout manager
titleNamePanel.setBackground(Color.black);
titleNameLabel = new JLabel("EPIC OF YEET");
titleNameLabel.setForeground(Color.red);
titleNameLabel.setFont(titleFont);
startButtonPanel = new JPanel();
//startButtonPanel.setBounds(400, 500, 400, 100);
startButtonPanel.setPreferredSize(new Dimension(400, 100));
startButtonPanel.setBackground(Color.black);
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
startButton.addActionListener(tsHandler);
startButton.setFocusPainted(false);
titleNamePanel.add(titleNameLabel);
startButtonPanel.add(startButton);
con.add(titleNamePanel, BorderLayout.PAGE_START); //set to top
con.add(startButtonPanel, BorderLayout.PAGE_END); //set to bottom
epicOfYeet.pack();
epicOfYeet.setVisible(true);
}
public void createGameScreen(){
//titleNamePanel.setVisible(false);
//startButtonPanel.setVisible(false);
con.remove(titleNamePanel);
con.remove(startButtonPanel);
mainTextPanel = new JPanel();
//mainTextPanel.setBounds(100, 100, 1000, 400);
mainTextPanel.setBackground(Color.green);
con.add(mainTextPanel); // added to center position of the BorderLayout (the default)
mainTextArea = new JTextArea(10, 20); //size in rows, cols
mainTextArea.setText("You come to your senses again.\nThe dewy grass you're laying on is gleaming with moonlight.\nYour body aches as you get up and catch a \nglimpse of your surroundings.\n");
//mainTextArea.setBounds(100, 100, 1000, 250);
mainTextArea.setBackground(Color.blue);
mainTextArea.setForeground(Color.white);
mainTextArea.setFont(normalFont);
mainTextArea.setLineWrap(true);
mainTextPanel.add(mainTextArea);
choiceButtonPanel = new JPanel();
//choiceButtonPanel.setBounds(300, 500, 600, 550);
choiceButtonPanel.setPreferredSize(new Dimension(600, 550));
choiceButtonPanel.setBackground(Color.red);
con.add(choiceButtonPanel, BorderLayout.PAGE_END);//add to bottom
epicOfYeet.pack();
}
public class TitleScreenHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
createGameScreen();
}
}
}

Not adding Card Layout in JFrame

Can anyone see the code ? I want to make a page that has a banner and a pannel in which cards will change on the requirement. I added the Banner in JFrame (That is working fine) but The problem is that " CardLayout Panel is not adding in the JFrame".
Actually, I need this.
When button is pressed only card1 change to card2 but banner will remain same.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class gui extends JFrame{
private static final long serialVersionUID = 1L;
JPanel
basic_panel,
card_Layout_panel,
banner_panel,
welcome_authenticaion_panel_card1;
CardLayout basic2;
JLabel
logo_label,
name_label;
public gui(){
server_login_gui();
add(basic_panel);
standard_gui();
}
public void server_login_gui(){
basic_panel = new JPanel();
basic_panel.setLayout(null);
basic_panel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
banner_panel = new JPanel();
banner_panel.setLayout(null);
banner_panel.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));
banner_panel.setSize(680, 200);//(400,100,400,100);
//////Banner inner things//////////////////////////////////////////////////
logo_label = new JLabel("Logo");
logo_label.setBounds(30,40,100,100);
logo_label.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
banner_panel.add(logo_label);
name_label = new JLabel(" Name..... ");
name_label.setFont(new Font("Times new Roman", Font.BOLD | Font.ITALIC,25));
name_label.setBounds(200,80,400,50);
name_label.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
banner_panel.add(name_label);
////////////////////////////////////////////////////////////////////////
// basic_panel.add(banner_panel,BorderLayout.NORTH);
///////// Card Layout//////////////
basic2 = new CardLayout();
card_Layout_panel = new JPanel(basic2);
card_Layout_panel.setBorder(BorderFactory.createLineBorder(Color.WHITE, 5));
basic_panel.add(card_Layout_panel,BorderLayout.CENTER);
welcome_authenticaion_panel_card1 = new JPanel();
welcome_authenticaion_panel_card1.setLayout(null);
welcome_authenticaion_panel_card1.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
welcome_authenticaion_panel_card1.setSize(680, 200);//(400,100,400,100);
welcome_authenticaion_panel_card1.setBounds(0,200,680,460);
card_Layout_panel.add(welcome_authenticaion_panel_card1, "1");
basic_panel.add(card_Layout_panel,BorderLayout.CENTER);
/////////////////////////////////////////////////////////////////////////
}
public void standard_gui(){
setSize(700,700);
setTitle("System");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}
I want to make a page that has a banner and a pannel in which cards
will change on the requirement.
your component aren't focusable, there is required some event (JButton, Swing Timer) for switching the view by using CardLayout
for more info about CardLayout to read Oracle tutorial, for working code exampes, tons code examples are here
you code works without NullLayout (by set BorderLayout to parent JPanel), default LayoutManager for Jpanel is FlowLayout (accepts only getPreferredSize, childs aren't resizable with its parent/s)
my question is for why reason is there code line basic_panel.add(card_Layout_panel, BorderLayout.CENTER); twice, and another ...
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Gui extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel basic_panel, card_Layout_panel,
banner_panel, welcome_authenticaion_panel_card1;
private CardLayout basic2;
private JLabel logo_label, name_label;
public Gui() {
server_login_gui();
add(basic_panel);
standard_gui();
}
public void server_login_gui() {
basic_panel = new JPanel();
basic_panel.setLayout(new BorderLayout(10, 10));
basic_panel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
banner_panel = new JPanel();
//banner_panel.setLayout(null);
banner_panel.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));
banner_panel.setSize(680, 200);//(400,100,400,100);
//////Banner inner things//////////////////////////////////////////////////
logo_label = new JLabel("Logo");
//logo_label.setBounds(30, 40, 100, 100);
logo_label.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
banner_panel.add(logo_label);
name_label = new JLabel(" Name..... ");
name_label.setFont(new Font("Times new Roman", Font.BOLD | Font.ITALIC, 25));
//name_label.setBounds(200, 80, 400, 50);
name_label.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
banner_panel.add(name_label);
////////////////////////////////////////////////////////////////////////
basic_panel.add(banner_panel, BorderLayout.NORTH);
///////// Card Layout//////////////
basic2 = new CardLayout();
card_Layout_panel = new JPanel(basic2);
card_Layout_panel.setBorder(BorderFactory.createLineBorder(Color.WHITE, 5));
basic_panel.add(card_Layout_panel, BorderLayout.CENTER);
welcome_authenticaion_panel_card1 = new JPanel();
welcome_authenticaion_panel_card1.setLayout(null);
welcome_authenticaion_panel_card1.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
welcome_authenticaion_panel_card1.setSize(680, 200);//(400,100,400,100);
//welcome_authenticaion_panel_card1.setBounds(0, 200, 680, 460);
card_Layout_panel.add(welcome_authenticaion_panel_card1, "1");
basic_panel.add(card_Layout_panel, BorderLayout.CENTER);
/////////////////////////////////////////////////////////////////////////
}
public void standard_gui() {
setSize(700, 700);
setTitle("System");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui();
}
});
}
}
you're doing this basic_panel.add(card_Layout_panel,BorderLayout.CENTER); twice, hence the error. ( check before and after the welcome_authentication_panel_card )

Adding 2 JLists to a JPanel using BorderLayout

I need to add 2 JLists inside a JPanel for a crossword. The JPanel is located SOUTH and I'm using BorderLayout in the constructor to locate the JPanel.
The problem is, I can't see the 2 JLists inside the JPanel
package crossword;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main extends JFrame implements MouseListener {
Container container;
//this is the constructor
public Main(){
super("Crossword");
container = getContentPane();
container.setLayout(new BorderLayout(1, 1));
container.setBackground(new Color(91,119,162));
container.add(login(),BorderLayout.NORTH);
container.add(buttons(),BorderLayout.WEST);
container.add(clues(),BorderLayout.SOUTH);
container.add(createMatrix(crosswordPanel()),BorderLayout.CENTER);
container.add(eastPanel(),BorderLayout.EAST);
}
public JPanel login(){
JPanel loginPanel = new JPanel();
loginPanel.setLayout(new FlowLayout(1, 15, 5));
loginPanel.setPreferredSize(new Dimension(8, 40));
loginPanel.setBackground(new Color(47,47,47));
loginPanel.setVisible(true);
JTextField inputUserName = new JTextField(15);
loginPanel.add(inputUserName);
JButton btnEnter = new JButton("Play!");
btnEnter.setPreferredSize(new Dimension(80,25));
loginPanel.add(btnEnter);
return loginPanel;
}
public JPanel buttons(){
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(5, 45, 15));
buttonsPanel.setPreferredSize(new Dimension(250, 200));
buttonsPanel.setBackground(new Color(91,119,162));
buttonsPanel.setVisible(true);
JButton newGame = new JButton("New game");
newGame.setPreferredSize(new Dimension(130,27));
newGame.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(newGame);
JButton showChar = new JButton("Reveal letter");
showChar.setPreferredSize(new Dimension(130,27));
showChar.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(showChar);
JButton showWord = new JButton("Reveal word");
showWord.setPreferredSize(new Dimension(130,27));
showWord.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(showWord);
JButton verifyWord = new JButton("Verify");
verifyWord.setPreferredSize(new Dimension(130,27));
verifyWord.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(verifyWord);
JButton revealAll = new JButton("Solution");
revealAll.setPreferredSize(new Dimension(130,27));
revealAll.setFont(new Font("Tahoma", Font.PLAIN, 11));
buttonsPanel.add(revealAll);
JLabel labelScore = new JLabel("Score:");
labelScore.setFont(new Font("Arial", Font.BOLD, 13));
buttonsPanel.add(labelScore);
return buttonsPanel;
}
public JPanel clues(){
JPanel clues = new JPanel();
clues.setLayout(new FlowLayout(3, 1, 1));
clues.setPreferredSize(new Dimension(200, 200));
clues.setBackground(new Color(91,119,162));
clues.setVisible(true);
JList horizontalList = new JList();
horizontalList.setBackground(Color.BLUE);
horizontalList.setBorder(BorderFactory.createEtchedBorder(1));
clues.add(horizontalList);
JList verticalList = new JList();
verticalList.setBackground(Color.ORANGE);
verticalList.setBorder(BorderFactory.createEtchedBorder(1));
clues.add(verticalList);
return clues;
}
public JPanel eastPanel(){
JPanel fill = new JPanel();
fill.setLayout(new FlowLayout(5, 25, 15));
fill.setPreferredSize(new Dimension(50, 200));
fill.setBackground(new Color(91,119,162));
fill.setVisible(true);
return fill;
}
public JPanel crosswordPanel(){
JPanel crosswordPanel = new JPanel();
crosswordPanel.setLayout(new GridLayout(10,10,0,0));
crosswordPanel.setBackground(Color.white);
//crosswordPanel.setPreferredSize(new Dimension(200, 200));
crosswordPanel.setBackground(new Color(91,119,162));
crosswordPanel.setVisible(true);
return crosswordPanel;
}
public JPanel createMatrix(JPanel crosswordPanel){
JPanel crosswordMatrix [][] = new JPanel [10][10];
for (int i = 0; i < crosswordMatrix.length ; i++) {
for (int j = 0; j < crosswordMatrix[0].length; j++) {
crosswordMatrix[i][j] = new JPanel();
crosswordMatrix[i][j].setBackground(Color.lightGray);
crosswordMatrix[i][j].setBorder(BorderFactory.createLineBorder(Color.black, 1));
crosswordMatrix[i][j].addMouseListener(this);
//crosswordMatrix[i][j].add(label);
crosswordPanel.add(crosswordMatrix[i][j]);
}
}
return crosswordPanel;
}
public static void main(String[] args) {
Main guiWindow = new Main();
Toolkit screenSize = Toolkit.getDefaultToolkit();
int width = screenSize.getScreenSize().width * 4/5;
int height = screenSize.getScreenSize().height * 4/5;
guiWindow.setSize(width, height);
guiWindow.setLocationRelativeTo(null);
guiWindow.setVisible(true);
guiWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Its not an MCVE, but based upon the limited code you posted: in the clues method a JPanel is constructed, yet nothing is ever added to it. Rather, you add the JLists directly to the object which contains the method (which I presume this extends JFrame). Perhaps try adding the components to the JPanel
public JPanel clues(){
JPanel clues = new JPanel();
...
clues.add(horizontalList);
....
clues.add(verticalList);
}

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