I have simple problem as I am not much familiar with Java GUI. I am trying to make visible the JLable on the below code as I find it hard to understand the concept. But still label is not visible but the frame do open on run time.
public class Sample extends JPanel {
public void Sample() {
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Sample());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
You are forgot to add panel p to sample. Either use add(p) at the end or just remove panel p cause your sample class is extending JPanel.
Option 1:
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
add(p);
option 2:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
setLayout(new FlowLayout());
add(lab1 = new JLabel("add JLabel"));
Also why are you overriding initialization of JLabel? In your code JLable will always hold value "add JLabel". If you want to see "User Name" then use this add(lab1); instead of add(lab1 = new JLabel("add JLabel"));.
May be you just require this:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
setLayout(new FlowLayout());
add(lab1);
Also constructor can not have return type so remove void from your constructor.
The constructor that you are using is not a proper constructor .. A java constructor does not have a return type and the void is extra. When in the main method you are calling new Sample() it is not actually calling your method but the default constructor that exists by default.
Try like this ..
public Sample() {
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
}
also you need to do what #Harry Joy suggested to add the add(p); statement otherwise the panel is still not added.
Note the comments.
import java.awt.*;
import javax.swing.*;
public class Sample extends JPanel {
public Sample() {
// set the layout in the constructor
super(new FlowLayout(FlowLayout.LEADING));
// best not to set size OR preferred size!
setPreferredSize( new Dimension(200,200) );
JLabel lab1 = new JLabel("User Name");
add(lab1);
}
public static void main(String[] args) {
// construct the GUI on the EDT
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame("User Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Sample());
// important!
frame.pack();
frame.setVisible(true);
}
});
}
}
Note also, that it is generally not considered a good idea to extend a component unless adding custom functionality. That would mean (for example) defining new methods for the Sample panel (Which might better be labelled a UserDetails or UserDetailsContainer if I guess correctly where you are going with that code..). Or it might be a Login component..
Sample is the Jpanel.
Sample extends JPanel means you inherit from JPanel.
just drop JPanel p and all your "p."s
#SuppressWarnings("serial")
public class MyGui extends JFrame{
private MyContentPane myContentPane = new MyContentPane();
public MyGui(){
super("title");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(myContentPane);
this.createMenu();
this.pack();
this.setVisible(true);
}
private void createMenu(){
JMenuBar myMenuBar = new JMenuBar();
JMenu xMenu = new JMenu("x");
JMenu x = new JMenu("x");
JMenuItem xItem = new JMenuItem("letter");
JMenuItem exitItem = new JMenuItem("exit");
xItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
myContentPane.xPanel();
}
});
xItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
myContentPane.setxPanel();
}
});
exitItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
displayMenu.add(letterItem);
displayMenu.add(colorItem);
fileMenu.add(exitItem);
myMenuBar.add(displayMenu);
myMenuBar.add(fileMenu);
this.setJMenuBar(myMenuBar);
}
}
Related
I am making an UI in a minecraft plugin. Everything is working, except I have a JPanel and it doesn't fill the whole JFrame. So what I want is the JPanel fill the entire JFrame even if we re-scale the window.
I use Layout manager (FlowLayout) for the JPanel.
I tried using a Layout manager for the JFrame, well it didn't solved my problem because it didn't resize the JPanel.. I tried setting the size of the JPanel to the JFrame's size, but when it's resized it doesn't scale with it.
So, how can I do this?
My plugin creates a button for every player and when I click the button it kicks the player.
My code (I can't really post less because I don't know where I need to change something):
public static JFrame f;
public static JTextField jtf;
public static JPanel jp;
public static void creategui()
{
System.out.println("GUI created.");
f = new JFrame("Players");
jp = new JPanel();
jp.setLayout(new FlowLayout(FlowLayout.LEFT));
jp.setBackground(Color.GRAY);
jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setSize(new Dimension(200,200));
f.setLayout(null);
f.setSize(500,500);
f.setVisible(true);
jp.add(jtf);f.add(jp, BorderLayout.CENTER);
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
Bukkit.getPlayer(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
jp.add(b);
System.out.println("Button added.");
}
f.add(jp, BorderLayout.CENTER);
}
The question should include an mcve reproducing the problem so we can test it.
It could look like this :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Mcve {
private static List<String> players = Arrays.asList(new String[]{"Player A", "Player B"});
public static void main(String[] args) {
creategui();
}
public static void creategui()
{
JPanel jp = new JPanel();
jp.setBackground(Color.GRAY);
JTextField jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setSize(new Dimension(200,200));
jp.add(jtf);
for (final String p : players)
{
final JButton b = new JButton();
b.setText(p);
b.setBackground(Color.GREEN);
b.addActionListener(e -> {
if (!b.getBackground().equals(Color.RED))
{
b.setBackground(Color.RED);
}
});
jp.add(b);
}
JFrame f = new JFrame("Players");
f.setLayout(null);
f.setSize(500,500);
f.add(jp, BorderLayout.CENTER);
f.setVisible(true);
}
}
To make the JPanel fill the entire frame simply remove this line :
f.setLayout(null);
and let the default BorderLayout manager do its work.
Here is a modified version with some additional comments:
public class Mcve {
private static List<String> players = Arrays.asList(new String[]{"Player A", "Player B"});
public static void main(String[] args) {
creategui();
}
public static void creategui()
{
JPanel jp = new JPanel();
jp.setBackground(Color.GRAY);
JTextField jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setPreferredSize(new Dimension(250,200)); // set preferred size rather than size
jp.add(jtf);
for (final String p : players)
{
final JButton b = new JButton();
b.setText(p);
b.setBackground(Color.GREEN);
b.addActionListener(e -> {
if (!b.getBackground().equals(Color.RED))
{
b.setBackground(Color.RED);
}
});
jp.add(b);
}
JFrame f = new JFrame("Players");
//f.setLayout(null); null layouts are bad practice
//f.setSize(500,500); let layout managers set the sizes
f.add(jp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
A 1x1 grid layout does the job quite nicely.
window = new JFrame();
panel = new JPanel();
window.setLayout(new java.awt.GridLayout(1, 1));
window.add(panel);
Either set the layout manager for jp (the JPanel in the code you posted) to BorderLayout and add jtf (the JTextField in the code you posted) to the CENTER of jp, as in:
f = new JFrame();
jp = new JPanel(new BorderLayout());
jtf = new JTextField(30); // number of columns
jp.add(jtf, BorderLayout.CENTER);
f.add(jp, BorderLayout.CENTER);
or dispense with jp and add jtf directly to f (the JFrame in the code you posted), as in:
f = new JFrame();
jtf = new JTextField(30);
f.add(jtf, BorderLayout.CENTER);
The key is that the CENTER component of BorderLayout expands to fill the available space.
So I fixed it somehow, this is the code:
public static void creategui()
{
System.out.println("GUI created.");
f = new JFrame("Players");
jp = new JPanel();
jp.setBackground(Color.GRAY);
jp.setSize(200,200);
jtf = new JTextField(30);
jtf.setToolTipText("Write the reason here.");
jp.add(jtf);
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
getplr(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
jp.add(b);
System.out.println("Button added.");
}
f.setLayout(new BorderLayout());
f.add(jp, BorderLayout.CENTER);
f.setSize(500,500);
f.pack();
f.setVisible(true);
}
I can't seem to figure out why my JFrame is empty. Where am I going wrong?
import javax.swing.*;
import java.awt.FlowLayout;
public class GUIExample extends JFrame {
JCheckBox box1 = new JCheckBox("Satellite Radio");
JCheckBox box2 = new JCheckBox("Air Conditioning");
JCheckBox box3 = new JCheckBox("Manual Tranmission");
JCheckBox box4 = new JCheckBox("Leather Seats");
JRadioButton radio1 = new JRadioButton("Car");
JRadioButton radio2 = new JRadioButton("Pickup Truck");
JRadioButton radio3 = new JRadioButton("Minivan");
JTextField text = new JTextField();
ButtonGroup group = new ButtonGroup();
public void newGUI() {
setLayout(new FlowLayout());
JPanel panel = new JPanel();
JPanel textPanel = new JPanel();
add(textPanel);
add(panel);
panel.add(box1);
panel.add(box2);
panel.add(box3);
panel.add(radio1);
panel.add(radio2);
panel.add(radio3);
group.add(radio1);
group.add(radio2);
group.add(radio3);
}
public static void main(String[] args) {
JFrame frame = new JFrame("GUI Example");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
You forgot to add the contentPane in your jFrame, something like this
frame.setContentPane(panel);
I notice you're using inheritance to build your jFrame, so in this case you need to instantiate your own class. I've refactored your code with the minimun to run an jFrame.
public class GUIExample extends JFrame {
JCheckBox box1 = new JCheckBox("Satellite Radio");
public static void main(String[] args) {
JFrame frame = new GUIExample("GUI Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(box1);
frame.setContentPane(panel);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Basically you create an JFrame, create an JPanel, add your components to this panel and set the panel to your frame with setContentPane(panel).
I'm sorry I can't test this right now, so if someone could and fix if needed, would really appreciate, but is something like this.
First of all this is quite a good try to what you are trying to do. However there seem to be some basic misunderstandings as to how you are coding the GUI.
There are two ways of making a GUI in java. Either you create frames and panel objects then add your components to them, or you can create and extend your own classes by extends JFrame. But in this case you have tried to do both. You have extended JFrame and you have created the Objects.
I actually quite like how you've tried to extended the JFrame, so I've continued this and made code that add stuff to your screen!
See below - GUIExample.java:
import javax.swing.*;
import java.awt.FlowLayout;
public class GUIExample extends JFrame {
JCheckBox box1 = new JCheckBox("Satellite Radio");
JCheckBox box2 = new JCheckBox("Air Conditioning");
JCheckBox box3 = new JCheckBox("Manual Tranmission");
JCheckBox box4 = new JCheckBox("Leather Seats");
JRadioButton radio1 = new JRadioButton("Car");
JRadioButton radio2 = new JRadioButton("Pickup Truck");
JRadioButton radio3 = new JRadioButton("Minivan");
JTextField text = new JTextField();
ButtonGroup group = new ButtonGroup();
GUIExample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
newGUI();
}
public void newGUI() {
setLayout(new FlowLayout());
JPanel panel = new JPanel();
JPanel textPanel = new JPanel();
add(textPanel);
add(panel);
panel.add(box1);
panel.add(box2);
panel.add(box3);
panel.add(radio1);
panel.add(radio2);
panel.add(radio3);
group.add(radio1);
group.add(radio2);
group.add(radio3);
}
}
test.java:
public class test {
public static void main(String[] args) {
GUIExample e = new GUIExample();
}
}
To get this working. Compile both of the files and then run your program through test.java.
Moreover your original solution, nowhere did you add a newGUI() call so all that code becomes redundant. However as the main method is static, you wouldn't be able to call it anyways.
I hope this helps!
For some reason the AddListener class below doesn't work, and I keep getting a number format exception. Could anyone please tell me the reason for this. It seems to me as if it should work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculator extends JFrame {
JFrame theFrame = this;
JTextField addField; // Declaring this here so that you can access the variable from other places. MAKE SURE TO NOT DECLARE THIS AGAIN IN THE CONSTRUCTOR
JTextField totalField;
public BabyCalculator() {
//You set this up so that you can refer to the frame using the inner class below.
setDefaultCloseOperation(EXIT_ON_CLOSE);
setName("Baby Calculator");
setLayout(new GridLayout(3, 0));
//add
JLabel addLabel = new JLabel("Amount to add:");
addField = new JTextField(10);
JButton addButton = new JButton("add");
addButton.addActionListener(new AddListener());
//multiply
JLabel multiplyLabel = new JLabel("Amount to multiply:");
JTextField multiplyField = new JTextField(10);
JButton multiplyButton = new JButton("multiply");
//total
JLabel totalLabel = new JLabel("Total");
totalField = new JTextField(10);
totalField.setEditable(false);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
//Create Panels
JPanel topRow = new JPanel(new BorderLayout());
JPanel middleRow = new JPanel(new BorderLayout());
JPanel bottomRow = new JPanel(new FlowLayout());
//Add the top Row
topRow.add(addLabel, BorderLayout.WEST);
topRow.add(addField, BorderLayout.CENTER);
topRow.add(addButton, BorderLayout.EAST);
add(topRow);
middleRow.add(multiplyLabel, BorderLayout.WEST);
middleRow.add(multiplyField, BorderLayout.CENTER);
middleRow.add(multiplyButton, BorderLayout.EAST);
add(middleRow);
bottomRow.add(totalLabel);
bottomRow.add(totalField);
bottomRow.add(stopButton);
add(bottomRow);
pack();
setVisible(true);
}
public class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String addFieldText = addField.getText();
String totalFieldText = totalField.getText();
double addAmount = Double.parseDouble(addFieldText);
double total = Double.parseDouble(totalFieldText);
total += addAmount;
totalField.setText(total + "");
}
}
//end class AddListener
public class StopListener implements ActionListener {//this is an inner class
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(theFrame, "You Clicked the stop button");
}//end class StopListener
}
public static void main(String[] args) {
JFrame newFrame = new BabyCalculator();
}
}
Note: The problem in the code is definitely related to the AddListener. Whenever I click the add button in the GUI I get an exception.
The problem is with the totalFieldText, it's default value is blank, meaning that when you try and convert to a double value, it causes a NumberFormatException
Try giving it a default value of 0, for example
totalField = new JTextField("0", 10);
You might also like to take a look at How to Use Spinners and How to Use Formatted Text Fields which will make your life easier
I have constructed a class for the JPanel with several JButtons.Inside this class I want to construct another JPanel with JLabels that will change depending on the actionPerformed on the JButtons of the first JPanel.Finally, I want to add these 2 panels on the same Jframe. Can all these be done within the class of the first Panel?Otherwise, which is a better approach for this problem?
Yes, you can. One way you could accomplish this is with anonymous inner classes (saves keystrokes):
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
public class Foo {
JLabel one;
JLabel two;
public static void main(String[] args) {
(new Foo()).go();
}
public void go() {
JFrame frame = new JFrame("Test");
// Panel with buttons
JPanel buttonPanel = new JPanel();
JButton changeOne = new JButton("Change One");
changeOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
one.setText("New text for one");
}
}
buttonPanel.add(changeOne);
JButton changeTwo = new JButton("Change Two");
changeTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
two.setText("New text for two");
}
}
buttonPanel.add(changeTwo);
frame.add(buttonPanel, BorderLayout.NORTH);
// Panel with labels
JPanel labelPanel = new JLabel();
one = new JLabel("One");
labelPanel.add(one);
two = new JLabel("Two");
labelPanel.add(two);
// Set up the frame
frame.add(labelPanel, BorderLayout.SOUTH);
frame.setBounds(50, 50, 500, 500);
frame.setDefaultCloseAction(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I am still learning Java and I am currently creating a program in Swing. I have been confused regarding when and when I should use methods and class files. I have created an application that has two cards, card 1: homeJPanel and card 2: guestFixturesJPanel and I want these to switch between each other on button click - which i have done to an extent. However, my code looks extremely messy and is hard to look at as all JPanels are in one method. I was wondering if there was any way I could put guestFixturesJPanel into a separate method or class file and still be able to call the card on button click. Is this possible? Also, does anyone know of any good tutorials that explain methods and class files well as I have been confused and this may be the solution to my problem.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
public class Main
{
protected static final Component c1 = null;
private JButton viewFixturesButton, loginButton, guestBackButton;
private JLabel testTextJLabel, testTextJLabel2;
JPanel container = new JPanel();
CardLayout cardLayout = new CardLayout();
public Main()
{
final JFrame window = new JFrame ("Main Game");
final CardLayout c1 = new CardLayout();
final JPanel container = new JPanel(c1);
JPanel homeJPanel = new JPanel(new BorderLayout());
container.add(homeJPanel);
JPanel centerJPanel = new JPanel(new BorderLayout());
testTextJLabel = new JLabel("TEST");
centerJPanel.add(testTextJLabel);
JPanel southPanel = new JPanel(new FlowLayout());
viewFixturesButton = new JButton("View Fixtures");
loginButton = new JButton("Login");
southPanel.add(viewFixturesButton);
southPanel.add(loginButton);
homeJPanel.add(centerJPanel, BorderLayout.CENTER);
homeJPanel.add(southPanel, BorderLayout.SOUTH);
centerJPanel.setBackground(Color.BLUE);
southPanel.setBackground(Color.GREEN);
JPanel guestFixturesJPanel = new JPanel(new BorderLayout());
container.add(guestFixturesJPanel);
JPanel guestCenterJPanel = new JPanel(new BorderLayout());
JPanel guestSouthPanel = new JPanel(new FlowLayout());
guestBackButton = new JButton("Back");
guestSouthPanel.add(guestBackButton);
guestFixturesJPanel.add(guestCenterJPanel, BorderLayout.CENTER);
guestFixturesJPanel.add(guestSouthPanel, BorderLayout.SOUTH);
guestCenterJPanel.setBackground(Color.BLUE);
guestSouthPanel.setBackground(Color.GREEN);
viewFixturesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
c1.show(container, "2");
}
});
container.add(homeJPanel, "1");
container.add(guestFixturesJPanel, "2");
c1.show(container, "1");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(container);
window.setSize(600, 500);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Main();
}
});
}
}
You could extract the guestFixturesPanel to a class of its own like this:
public class GuestFixturesPanel extends JPanel {
public GuestFixturesPanel() {
this.setLayout(new BorderLayout());
JPanel guestCenterJPanel = new JPanel(new BorderLayout());
JPanel guestSouthPanel = new JPanel(new FlowLayout());
JButton guestBackButton = new JButton("Back");
guestSouthPanel.add(guestBackButton);
add(guestCenterJPanel, BorderLayout.CENTER);
add(guestSouthPanel, BorderLayout.SOUTH);
guestCenterJPanel.setBackground(Color.BLUE);
guestSouthPanel.setBackground(Color.GREEN);
}
}
Then in your Main class you could instantiate a GuestFixturesPanel and add it to your container. This would preserve the functionality you have now, and extract the code out of your Main class.
GuestFixturesPanel guestFixturesPanel = new GuestFixturesPanel();
container.add(guestFixturesPanel, "2");
Not sure if that addresses the question you had, but I hope this helps.