Centering Swing Components - java

How do I make my textfields and button centered?
Edit: Updated my post with SSCE. Hopefully that helps.
By the way, I want the left image to look like the right.
package pkg;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class Game {
private static JPanel panel = new JPanel();
public static JTextField username = new JTextField(20);
public static JPasswordField password = new JPasswordField(20);
JButton login = new JButton("Login");
JLabel status = new JLabel();
private static JPanel game = new JPanel();
private JButton logout = new JButton("Logout");
private static JFrame frame = new JFrame("RuneShadows");
public Game() {
panel.add(username);
panel.add(password);
panel.add(login);
panel.add(status);
game.add(logout);
frame.add(panel);
frame.setSize(806, 553);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game();
}
public void loadGame() {
frame.remove(panel);
frame.revalidate();
frame.add(game);
frame.revalidate();
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(game);
frame.revalidate();
frame.add(panel);
frame.revalidate();
try {
Client.socketOut.writeUTF("logout");
Client.socketOut.writeUTF(Client.username);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
}
What I want it to look like:
I've tried to use many different layout styles but I can't seem to make it work...

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.border.*;
public class Game {
private static JPanel panel = new JPanel();
public static JTextField username = new JTextField(20);
public static JPasswordField password = new JPasswordField(20);
JButton login = new JButton("Login");
JLabel status = new JLabel();
private static JPanel game = new JPanel(new FlowLayout(FlowLayout.CENTER));
private JButton logout = new JButton("Logout");
private static JFrame frame = new JFrame("RuneShadows");
public Game() {
panel.setLayout(new GridLayout(0,1,15,15));
panel.setBorder(new EmptyBorder(50,100,50,100));
panel.add(username);
panel.add(password);
panel.add(status);
JPanel logoutConstrain = new JPanel(new FlowLayout(FlowLayout.CENTER));
logoutConstrain.add(logout);
panel.add(logoutConstrain);
frame.setLayout(new GridBagLayout());
frame.add(panel);
//frame.setSize(806, 553); // forget this nonsense, instead..
frame.pack(); // best!
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game();
}
public void loadGame() {
frame.remove(panel);
frame.revalidate();
frame.add(game);
frame.revalidate();
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(game);
frame.revalidate();
frame.add(panel);
frame.revalidate();
}
});
}
}

Related

Why this GUI counter can't display after 9?

I wrote this code and it works fine from 1 to 9 but after 9 instead of displaying numbers it displays ...
Can anyone tell me what could be the problem as am I quite new to GUI.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI implements ActionListener {
private int count = 0;
private JLabel label;
private JFrame frame;
private JPanel panel;
public GUI(){
frame = new JFrame();
panel = new JPanel();
JButton button = new JButton("Start");
button.addActionListener(this);
label = new JLabel("Number of Clicks: 0");
panel.setBorder(BorderFactory.createEmptyBorder(100,100,100,100));
panel.setLayout(new GridLayout(0,1));
panel.add(button);
panel.add(label);
frame.add(panel,BorderLayout.CENTER);
frame.setTitle("Clicker");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
#Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Number of Clicks: "+count);
}
}

ActionListener works but it never stops checking for user input and does not execute code after

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.KeyEvent;
public class Main {
String newLine = System.getProperty("line.separator");
public boolean isTrue = false;
public boolean isOn = false;
JFrame frame;
JLabel headerLabel;
JPanel controlPanel;
JTextArea textArea;
JTextField textField;
public Main (){
JPanel controlPanel = new JPanel();
JPanel buttonPanel = new JPanel();
frame = new JFrame("Test");
frame.setSize(800,600);
frame.setLayout(null);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
textArea = new JTextArea();
buttonPanel.add(textArea);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
controlPanel.add(scrollPane);
scrollPane.setVisible(true);
textField= new JTextField();
controlPanel.add(textField);
JButton btn = new JButton("btn");
buttonPanel.add(btn);
controlPanel.add(buttonPanel, BorderLayout.SOUTH);
headerLabel = new JLabel("", JLabel.CENTER);
frame.add(controlPanel);
frame.add(btn);
frame.add(headerLabel);
frame.add(textField);
frame.add(scrollPane);
frame.setVisible(true);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btn.setVisible(false);
textArea.append(newLine+"You pressed the btn");
isOn=true;
textField.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(isOn){
isOn=false;
isTrue=true;
String name=textField.getText();
textArea.append(newLine+"your chose the name"+name );
//... irrelevant code
if(isTrue){
System.out.println("This is true");
}
} else{
textArea.append(newLine+"Its not time yet.");
}
}
});
}
});
System.out.println(isTrue)
}
public static void main(String[] args) {
new Main();
}
}
Once the method reaches actionPerformed it seems to never leave. However whenever there is a new input in textField it prints out the statement in if isTrue but bellow the ActionListener isTrue is false. Some help understand correcting and understanding this would be fantastic.

Open new JFrame with JButton Click - Java Swing

I am trying to open a new JFrame window with a button click event. There is lots of info on this site but nothing that helps me because I think it is not so much the code I have, but the order it is executed (however I am uncertain).
This is the code for the frame holding the button that I want to initiate the event:
package messing with swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.border.EmptyBorder;
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<String> courseList = new ArrayList<String>();
public ReportGUI(){
reportInterface();
allReportsBtn();
examinnerFileRead();
courseFileRead();
comboBoxes();
}
private void examinnerFileRead(){
try{
Scanner scan = new Scanner(new File("Examiner.txt"));
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void courseFileRead(){
try{
Scanner scan = new Scanner(new File("Course.txt"));
while(scan.hasNextLine()){
courseList.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFrame AllDataGUI = new JFrame();
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = list.toArray(new String[list.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
String[] comboBox2Array = courseList.toArray(new String[courseList.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
add(panel, BorderLayout.LINE_START);
}
If you don't want to delve into the above code, the button ActionListener is here:
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
This is the code in the class holding the JFrame I want to open:
package messing with swing;
import java.awt.BorderLayout;
import java.awt.GridLayout;
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.JTextArea;
import javax.swing.border.EmptyBorder;
public class ViewCourseGUI extends JFrame{
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Courses taught by this examiner");
private JTextArea textArea = new JTextArea();
public void ViewCoursesGUI(){
panels();
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
Could someone please point me in the right direction?
As pointed out by PM 77-3
I had:
public void ViewCoursesGUI(){
panels();
}
When I should have had:
public ViewCourseGUI(){
panels();
}
A Combination of syntax and spelling errors.
Set the visibility of the JFrame you want to open, to true in the actionListener:
ViewCourseGUI viewCourseGUI = new ViewCourseGUI();
viewCourseGUI.setVisible(true);
This will open the new JFrame window once you click the button.
Let ReportGUI implement ActionListener. Then you will implement actionPerformed for the button click. On button click, create the second frame (if it doesn't exist). Finally, set the second frame visible (if it is currently not visible):
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ReportGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 8679886300517958494L;
private JButton button;
private ViewCourseGUI frame2 = null;
public ReportGUI() {
//frame1 stuff
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setLayout(new FlowLayout());
//create button
button = new JButton("Open other frame");
button.addActionListener(this);
add(button);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReportGUI frame = new ReportGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
if (frame2 == null)
frame2 = new ViewCourseGUI();
if (!frame2.isVisible())
frame2.setVisible(true);
}
}
}
This is a simple example. You'll have to add the rest of your code here.

I can use getActionCommand to change the label content, but I can't use it to change the color?

So with the help of others here I finally managed to code a button that alternates the label "Hello World!" to "Hello Universe!" and back again. I used the code below, and used the same way to try and change the color, but it didn't work as expected. I've been searching for hours on this, but with no avail. Thank you for reading, anything helps!
Code:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Javagame extends JPanel implements ActionListener{
protected JButton changetext;
protected JButton red;
protected JButton green;
private JLabel label;
public Javagame() {
add(changetext = new JButton("Button!"));
changetext.setPreferredSize(new Dimension(50, 50));
changetext.setActionCommand("change");
add(red = new JButton("Red"));
red.setPreferredSize(new Dimension(50, 50));
red.setActionCommand("changecolorRed");
add(green = new JButton("Green"));
green.setPreferredSize(new Dimension(50, 50));
green.setActionCommand("changecolorGreen");
changetext.addActionListener(this);
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
add(changetext, BorderLayout.NORTH);
add(red, BorderLayout.WEST);
add(green, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent e) {
if ("change".equals(e.getActionCommand())) {
label.setText("Hello Universe!");
changetext.setActionCommand("changeBack");
}
if ("changeBack".equals(e.getActionCommand())) {
label.setText("Hello World!");
changetext.setActionCommand("change");
}
if ("changecolorRed".equals(e.getActionCommand())) {
label.setForeground(new Color(0xFF0000));
}
if ("changecolorGreen".equals(e.getActionCommand())) {
label.setForeground(new Color(0x009900));
}
}
private static void createWindow(){
JFrame frame = new JFrame("Javagame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,500));
JPanel panel = new JPanel(new BorderLayout());
Javagame newContentPane = new Javagame();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}
You need to add ActionListeners to buttons for them to work.
This is usually done via a simple method call: red.addActionListener(someListener);
Also:
get rid of your setPreferredsize(...) method calls, and instead let components set their own size. At the most you can override getPreferredSize() if need be, but try to limit that.
Avoid having your GUI code implement your listener interfaces as that leads to confusing and difficult to manage code. Better to use anonymous inner listeners or private inner classes or stand alone listener classes.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaGame2 extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 400;
private static final Font LABEL_FONT = new Font("Arial", Font.BOLD, 20);
private static final Color[] FOREGROUNDS = { new Color(0x009900),
new Color(0x990000), new Color(0x000099), new Color(0x999900),
new Color(0x990099), new Color(0x009999) };
private static final String[] LABEL_TEXTS = { "Hello World!",
"Goodbye World!", "Hola Todo el Mundo!", "Hasta la Vista Baby!",
"Whatever!!" };
private JButton changetextButton;
private JButton changeColorButton;
private JLabel label;
private int labelTextIndex = 0;
private int foregroundIndex = 0;
public JavaGame2() {
label = new JLabel(LABEL_TEXTS[labelTextIndex], SwingConstants.CENTER);
label.setFont(LABEL_FONT);
label.setForeground(FOREGROUNDS[foregroundIndex]);
// example of anonymous inner ActionListener:
changetextButton = new JButton("Change Text");
changetextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
labelTextIndex++;
labelTextIndex %= LABEL_TEXTS.length;
label.setText(LABEL_TEXTS[labelTextIndex]);
}
});
// example of use of an anonymous AbstractAction:
changeColorButton = new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
foregroundIndex++;
foregroundIndex %= FOREGROUNDS.length;
label.setForeground(FOREGROUNDS[foregroundIndex]);
}
});
setLayout(new BorderLayout());
add(changetextButton, BorderLayout.NORTH);
add(changeColorButton, BorderLayout.SOUTH);
add(label, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JavaGame2 mainPanel = new JavaGame2();
JFrame frame = new JFrame("Java Game 2");
frame.setDefaultCloseOperation(JFrame.EXIT_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();
}
});
}
}

Adding image to Jbutton with foreground label

Friends, i m trying add image to my Jbutton using seticon method but it hide the text label on the button. Here is the code :
try {
Image img = ImageIO.read(getClass().getResource("image.jpg"));
studentsButton.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
And i m using swing in eclipse without init()/paint()/graphics, its simple frame in main method.
Simply use
studentsButton.setHorizontalTextPosition(AbstractButton.CENTER);
studentsButton.setVerticalTextPosition(AbstractButton.BOTTOM);
This will simply place the Text below the Image. And the output will be like this :
Here is one code example for your help having as output:
import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.imageio.ImageIO;
public class ButtonImageExample
{
private JButton imageButton;
private ImageIcon image;
private void displayGUI()
{
JFrame frame = new JFrame("Button Image Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
try
{
image = new ImageIcon(ImageIO.read(
new URL("http://i.imgur.com/6mbHZRU.png")));
}
catch(MalformedURLException mue)
{
mue.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
imageButton = new JButton("Button Text");
imageButton.setIcon(image);
imageButton.setHorizontalTextPosition(AbstractButton.CENTER);
imageButton.setVerticalTextPosition(AbstractButton.BOTTOM);
contentPane.add(imageButton);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ButtonImageExample().displayGUI();
}
});
}
}
LATEST EDIT : REGARDING ADDING BACKGROUND IMAGE THROUGH JLABEL
import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.imageio.ImageIO;
public class ButtonImageExample
{
private ImageIcon image, imageForLabel;
private JLabel imageLabel;
private JTextField userField;
private JPasswordField passField;
private JButton loginButton;
private void displayGUI()
{
JFrame frame = new JFrame("Button Image Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
try
{
image = new ImageIcon(ImageIO.read(
new URL("http://i.imgur.com/jwyrvXC.gif")));
imageForLabel = new ImageIcon(ImageIO.read(
new URL("http://i.imgur.com/09zgEvG.jpg")));
}
catch(MalformedURLException mue)
{
mue.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
imageLabel = new JLabel(imageForLabel);
JPanel basePanel = new JPanel();
// setOpaque(false) is used to make the JPanel translucent/transparent.
basePanel.setOpaque(false);
basePanel.setLayout(new BorderLayout(5, 5));
JPanel topPanel = new JPanel();
topPanel.setOpaque(false);
topPanel.setLayout(new GridLayout(2, 2, 5, 5));
JLabel userLabel = new JLabel("USERNAME : ", JLabel.CENTER);
userLabel.setForeground(Color.WHITE);
userField = new JTextField(10);
JLabel passLabel = new JLabel("PASSWORD : ", JLabel.CENTER);
passLabel.setForeground(Color.WHITE);
passField = new JPasswordField(10);
topPanel.add(userLabel);
topPanel.add(userField);
topPanel.add(passLabel);
topPanel.add(passField);
JPanel bottomPanel = new JPanel();
bottomPanel.setOpaque(false);
loginButton = new JButton("Click to LOGIN");
loginButton.setIcon(image);
loginButton.setHorizontalTextPosition(AbstractButton.CENTER);
loginButton.setVerticalTextPosition(AbstractButton.BOTTOM);
bottomPanel.add(loginButton);
basePanel.add(topPanel, BorderLayout.CENTER);
basePanel.add(bottomPanel, BorderLayout.PAGE_END);
imageLabel.setLayout(new GridBagLayout());
imageLabel.add(basePanel);
contentPane.add(imageLabel, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ButtonImageExample().displayGUI();
}
});
}
}
Here is the output of the same :

Categories

Resources