JTextField not visible in invoked method - java

I'm trying to populate a Panel with a textfield and a label, the label is being reflecting as expected, however the textfield is not showing up.
Below is the code that is being used:
package qmutility;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class panetest1
{
public static void main(String[] args)
{
createSubframe();
}
public static void createSubframe()
{
final JFrame subframe = new JFrame("Object Choice");
subframe.setSize(1000, 500);
subframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
subframe.getContentPane().setLayout(new GridLayout(1, 1));
JTextArea out = new JTextArea();
out.setEditable (false);
JScrollPane jp = new JScrollPane(out);
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel queue = new JPanel();
JLabel lblqname = new JLabel("Please enter the queue name");
JTextField txtqname = new JTextField(20);
queue.add(lblqname, txtqname);
JPanel chl = new JPanel();
tabbedPane.addTab("Queues", queue);
tabbedPane.addTab("Channels", chl);
subframe.getContentPane().add(tabbedPane);
subframe.getContentPane().add(jp);
tabbedPane.setVisible(true);
subframe.setVisible(true);
}
}
Edit: Attached the screengrabresult

Try changing the Layout of your panel.
Like, queue.setLayout(new FlowLayout());
or Add components to panel one by one,
queue.add(lblqname);
queue.add(txtqname);

The method Container.add(Component comp,Object constraints) adds a given Component with given constraints, it is not meant to add two Component at once.
Replace :
queue.add(lblqname, txtqname);
With
queue.add(lblqname);
queue.add(txtqname);

Related

Java Swing Alignment problem with BoxLayout

I have three components inside a top to down boxLayout (JLabel, JTextField, JButton). The problem is that when i set the X alignment for the label it looks as if i would've changed the X alignment of the button and vice versa, only when both have the same alignment it works fine.
When the screen gets wider both components take a weird alignment.
when both components have the same alignment everything works fine.
here is my code:
public void create(){
JPanel panel = new JPanel();
BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(boxLayout);
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel etiqueta = new JLabel("Numero de consultorio: ");
etiqueta.setBackground(Color.BLUE);
etiqueta.setOpaque(true);
etiqueta.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(etiqueta);
JTextField consultorio = new JTextField();
panel.add(consultorio);
JButton registrar = new JButton("Registrar");
registrar.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(registrar);
this.getContentPane().add(panel, BorderLayout.CENTER);
}
Here is the proposed by Andrew Thompson solution:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class TestFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TestFrame()::create);
}
private void create() {
JPanel panel = new JPanel();
BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(boxLayout);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel etiqueta = new JLabel("Numero de consultorio: ");
etiqueta.setBackground(Color.BLUE);
etiqueta.setOpaque(true);
JPanel layout = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
layout.add(etiqueta);
panel.add(layout);
JTextField consultorio = new JTextField();
panel.add(consultorio);
JButton registrar = new JButton("Registrar");
layout = new JPanel(new FlowLayout(FlowLayout.TRAILING, 0, 0));
layout.add(registrar);
panel.add(layout);
JFrame frm = new JFrame("Test");
frm.getContentPane().add(panel, BorderLayout.CENTER);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}

java not displaying jpanel in jframe after button press

I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...

JButton does not open JDialog

I am building a simple program. I have a class that extends from JDialog and class that extends from JFrame and is GUI of the application. I implemented ActionListener which should open the dialog after clicking on the JButton. Nothing happens though and I can't figure out why.
GUI
package nemocnice_sam;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class App extends JFrame {
JTable tbl = new JTable();
JButton pridejPacienta = new JButton("Přidej pacienta");
JButton smazPacienta = new JButton("Smaž pacienta");
JButton export = new JButton("Export");
JButton konec = new JButton("Konec");
JPanel panel = new JPanel();
PacientDialog novyPacient;
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == pridejPacienta){
novyPacient = new PacientDialog();
novyPacient.setModal(true);
novyPacient.setVisible(true);
}
}
};
SeznamPacientu pacienti = new SeznamPacientu();
ModelPacientu model = new ModelPacientu(pacienti);
public static void main(String[] args) {
new App();
}
public App() {
setLayout(new BorderLayout());
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(pridejPacienta);
panel.add(smazPacienta);
panel.add(export);
panel.add(konec);
add(panel,BorderLayout.NORTH);
tbl.setModel(model);
add(new JScrollPane(tbl), BorderLayout.CENTER);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
}
DIALOG CLASS
package nemocnice_sam;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class PacientDialog extends JDialog {
JTextField jmeno = new JTextField();
JTextField prijmeni = new JTextField();
JTextField rc = new JTextField();
JTextField cp = new JTextField();
JButton ok = new JButton("OK");
public PacientDialog(){
setLayout(new GridLayout(5,2));
add(new JLabel("Jméno:"));
add(jmeno);
add(new JLabel("Příjmení:"));
add(prijmeni);
add(new JLabel("RČ:"));
add(rc);
add(new JLabel("ČP:"));
add(cp);
pack();
}
}
You need to define the actionListener in button.
konec.addActionListener(al);
Defining an ActionListener alone is not sufficient.
In order to do its job, that listener must be registered with some component that actually sends Events to that Listener.
So you have it to add to the corresponding button for example, like:
pridejPacienta.addActionListener(al);
Besides: when you do that, you do not need that if (source == check within your action listener. You see, when each button has a distinct listener, then there will not be different sources.
You only need such kinds of checks when you want to attach the same ActionListener to multiple buttons!

How do I add a background image on a JFrame using a JLabel?

I am trying to display a background image on the JFrame using a JLabel. The code runs and the buttons appear, but the image does not. I have researched for solutions, yet I have not found one for my code specifically. Any help would be greatly appreciated.
/**
* Adds details to interface and programs buttons
*
* Imani Davis
* Final Project
*/
import java.awt.*;
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.border.EmptyBorder;
public class Use_PF_Interface extends JFrame implements Pet_Fish_Interface
{
// instance variables - replace the example below with your own
private JFrame window;
private JPanel panel1, panel2, panel3;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
/**
* Constructor for objects of class Use_PF_Interface
*/
public Use_PF_Interface()
{
setTitle("Virtual Pet Fish");
setSize(650, 650);
//initializes panels and panel layout
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel1.setLayout(new FlowLayout());
panel2.setLayout(new FlowLayout());
panel3.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("C:\\Users\\This PC\\Desktop\\OCEAN2.JPEG"));
panel1.add(lblBackgroundImage);
validate();
//adds button to panels
panel2.add(feedButton);
panel2.add(playGamesButton);
//add panels to frame
add(panel1);
add(panel2);
}
}
JFrame uses a BorderLayout by default, a BorderLayout can only manage a single component within any of the five available positions it provides, this means that panel2 is most likely the only component getting shown.
An alternative is to add you components to the JLabel, but remember, JLabel doesn't have a default layout manager. Also, remember, JLabel only uses the icon and text properties to calculate its preferred size, so if the contents require more space, they will be clipped.
Start by having a look at How to Use BorderLayout for more details
Also, remember, most Swing components are opaque generally, so you need to set them transparent when you want to do something like this
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Use_PF_Interface extends JFrame {
// instance variables - replace the example below with your own
private JPanel panel2;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
/**
* Constructor for objects of class Use_PF_Interface
*/
public Use_PF_Interface() {
setTitle("Virtual Pet Fish");
setSize(650, 650);
//initializes panels and panel layout
panel2 = new JPanel();
panel2.setOpaque(false);
panel2.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("..."));
lblBackgroundImage.setLayout(new BorderLayout());
//adds button to panels
panel2.add(feedButton);
panel2.add(playGamesButton);
lblBackgroundImage.add(panel2);
add(lblBackgroundImage);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Use_PF_Interface();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Try this,
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}

How to make radio buttons change text dynamically in Java

I'm fairly new to GUI. I'm trying to make it so that depending on which radio button is selected, a JLabel changes its value. For example, if "id" is selected, it'll display "http://steamcommunity.com/id/" and if "profile" is selected, it'll display "http://steamcommunity.com/profiles/". I have some code up and running and it's nearly complete:
package sgt;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class RadioButtonPrompt extends JPanel
implements ActionListener {
private static final long serialVersionUID = 1L;
static String idString = "ID";
static String profileString ="Profile";
static String type = idString;
public RadioButtonPrompt() {
super(new BorderLayout());
// Create radio buttons.
JRadioButton idButton = new JRadioButton(idString, true);
idButton.setMnemonic(KeyEvent.VK_I);
idButton.setActionCommand(idString);
JRadioButton profileButton = new JRadioButton(profileString);
profileButton.setMnemonic(KeyEvent.VK_P);
profileButton.setActionCommand(profileString);
// Group radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(idButton);
group.add(profileButton);
idButton.addActionListener(this);
profileButton.addActionListener(this);
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(idButton);
radioPanel.add(profileButton);
JPanel textPanel = new JPanel ();
JLabel URL = new JLabel(setJLabelValue());
JTextField text = new JTextField("sampletextfield");
text.setPreferredSize(new Dimension(100, 20));
textPanel.add(URL);
textPanel.add(text);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0));
JButton submit = new JButton("Submit");
submit.setMnemonic(KeyEvent.VK_S);
buttonPanel.add(submit);
add(radioPanel, BorderLayout.LINE_START);
add(textPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
setBorder(BorderFactory.createCompoundBorder());
}
private String setJLabelValue() {
if (type.equals("ID")) {
return "http://steamcommunity.com/id/";
}
return "http://steamcommunity.com/profiles/";
}
public void actionPerformed(ActionEvent e) {
// Returns either "Profile" or "ID"
type = ((JRadioButton)e.getSource()).getText();
System.out.println(type);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Steam Game Tracker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new RadioButtonPrompt();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Take a look at this SO thread.
in actionPerformed() you need to textpanel.setText() to whatever you want based on which button was clicked. I'm guessing at the method name, haven't done any UI stuff with Java for a while.

Categories