How to update LookAndFeel in Java? - java

I have written a program that updates the LookAndFeel on a test GUI first. Once the user clicks the "select" button, the LookAndFeel is passed to a main GUI method that creates a new window using that selection.
It works fine. Although, as the user cycles through the various LookAndFeels, the test GUI does not really update and show the changes. Each time the change button is clicked I have it update and display the current LookAndFeel(and repain();), so I know it is changing. Also, when you hit select, the new GUI is created using whatever option you were on at the time(even though the test GUI window was not showing the changes).
What am I doing wrong?
import javax.swing.*; //UI.Manager <-- available
import java.awt.*;
import java.awt.event.*;
import javax.swing.UIManager.*;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.net.URL;
public class gui1 {
static JFrame frame1, testFrame;
static Container pane, testPane;
static JButton btnConnect, btnDisconnect, changeButton, selectButton;
static JLabel lblServer, lblUsername, lblPassword, lblPort, testLabel;
static JTextField txtServer, txtUsername, txtPassword, txtPort;
static Insets insets;
static JTextArea area, testArea;
public JScrollPane scroller, testScroller;
static int currentIndex;
URL frameImage;
Image img;
static boolean LookAndFeelSelected;
public static void main(String[] args){
gui1 begin = new gui1();
}
public gui1() {
//build our test gui & components
testFrame = new JFrame("Select which LookAndFeel you prefer..");
testFrame.setSize(375, 250);
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testLabel = new JLabel("Text Example", JLabel.CENTER);
testArea = new JTextArea(300,200);
testPane = testFrame.getContentPane();
changeButton = new JButton("Change");
selectButton = new JButton("Select");
testScroller = new JScrollPane(testArea);
testScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
testScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
testPane.add(changeButton);
testPane.add(selectButton);
testFrame.getContentPane().add(BorderLayout.WEST, changeButton);
testFrame.getContentPane().add(BorderLayout.EAST, selectButton);
testFrame.getContentPane().add(BorderLayout.CENTER, testScroller);
testFrame.getContentPane().add(BorderLayout.NORTH, testLabel);
changeButton.addActionListener(new changeListener());
selectButton.addActionListener(new selectListener());
testFrame.setVisible(true);
while(!LookAndFeelSelected) {
try{
Thread.sleep(500);
}catch(InterruptedException ex) {ex.printStackTrace();}
}
System.out.println("Selected!");
//start the real GUI with selected LookAndFeel
testFrame.dispose();
buildGui(UIManager.getLookAndFeel());
}
public void buildGui(LookAndFeel chosen){
//The frame and panel
frame1 = new JFrame("Sample GUI Application");
frame1.setSize(800, 230);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane = frame1.getContentPane();
pane.setLayout(null);
insets = pane.getInsets();
//Set the image
try{
frameImage = new URL("http://i.imgur.com/jMaYO1f.jpg");
img = ImageIO.read(frameImage);
}catch(IOException ex){ex.printStackTrace();}
frame1.setIconImage(img);
//Construct our objects for gui
btnConnect = new JButton("Connect");
btnDisconnect = new JButton("Disconnect");
lblServer = new JLabel("Remote Host: ");
lblUsername = new JLabel("Username: ");
lblPassword = new JLabel("Password: ");
lblPort = new JLabel("Port #");
txtServer = new JTextField(10);
txtPassword = new JTextField(10);
txtUsername = new JTextField(10);
txtPort = new JTextField(5);
area = new JTextArea(700, 125);
area.setLineWrap(true);
area.setEditable(false);
scroller = new JScrollPane(area);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//Add components to the pane
pane.add(lblServer);
pane.add(lblServer);
pane.add(lblPassword);
pane.add(lblUsername);
pane.add(lblPort);
pane.add(txtServer);
pane.add(txtPort);
pane.add(txtPassword);
pane.add(txtUsername);
pane.add(btnConnect);
pane.add(btnDisconnect);
pane.add(scroller); //includes area and scroller!
//Arrange our components in the pane
lblServer.setBounds(insets.left + 5, insets.top + 5, lblServer.getPreferredSize().width, lblServer.getPreferredSize().height);
txtServer.setBounds(lblServer.getX() + lblServer.getWidth() + 5, insets.top + 5, txtServer.getPreferredSize().width, txtServer.getPreferredSize().height);
lblUsername.setBounds(txtServer.getX() + txtServer.getWidth() + 5, insets.top + 5, lblUsername.getPreferredSize().width, lblUsername.getPreferredSize().height);
txtUsername.setBounds(lblUsername.getX() + lblUsername.getWidth() + 5, insets.top + 5, txtUsername.getPreferredSize().width, txtUsername.getPreferredSize().height);
lblPassword.setBounds(txtUsername.getX() + txtUsername.getWidth() + 5, insets.top + 5, lblPassword.getPreferredSize().width, lblPassword.getPreferredSize().height);
txtPassword.setBounds(lblPassword.getX() + lblPassword.getWidth() + 5, insets.top + 5, txtPassword.getPreferredSize().width, txtPassword.getPreferredSize().height);
lblPort.setBounds(txtPassword.getX() + txtPassword.getWidth() + 5, insets.top + 5, lblPort.getPreferredSize().width, lblPort.getPreferredSize().height);
txtPort.setBounds(lblPort.getX() + lblPort.getWidth() + 5, insets.top + 5, txtPort.getPreferredSize().width, txtPort.getPreferredSize().height);
btnConnect.setBounds(txtPort.getX() + txtPort.getWidth() + 5, insets.top + 5, btnConnect.getPreferredSize().width, btnConnect.getPreferredSize().height);
btnDisconnect.setBounds(insets.left + 5, lblServer.getY() + lblServer.getHeight() + 15, btnDisconnect.getPreferredSize().width, btnDisconnect.getPreferredSize().height);
scroller.setBounds(insets.left + 5, btnDisconnect.getX() + btnDisconnect.getHeight() + 33, 760, 125);
//Add button listeners
btnConnect.addActionListener(new connectListener());
btnDisconnect.addActionListener(new disconnectListener());
//Change the Look & Feel
try {
UIManager.setLookAndFeel(chosen);
} catch (Exception ex) {ex.printStackTrace();}
frame1.setVisible(true);
frame1.setResizable(false);
}
public static class connectListener implements ActionListener {
public void actionPerformed(ActionEvent event){
String toField = String.format("ServerIP: %s \t Username: %s \t Password: %s \t Port: %s\n", txtServer.getText(), txtUsername.getText(),
txtPassword.getText(), txtPort.getText());
area.append(toField);
}
}
public static class disconnectListener implements ActionListener {
public void actionPerformed(ActionEvent event){
area.append("Disconnected ..\n");
}
}
// Here only for initial LookAndFeel selection!
public static class changeListener implements ActionListener {
public void actionPerformed(ActionEvent event){
LookAndFeelInfo[] lafArray = UIManager.getInstalledLookAndFeels(); //not actual LookAndFeel(just name), thus use LookAndFeelInfo
try {
if (currentIndex == lafArray.length - 1) {
currentIndex = 0;
System.out.println("You have seen all Look and Feels, starting over .. \n\n");
}
UIManager.setLookAndFeel(lafArray[currentIndex++].getClassName());
testFrame.getContentPane().validate();
testFrame.getContentPane().repaint(); //repaint the frame to update changes
}catch(Exception ex) {ex.printStackTrace();}
String LookAndFeelName = String.format("Changed to: %s",UIManager.getLookAndFeel().getClass()); //gets current and displays name
System.out.println(LookAndFeelName);
}
}
public static class selectListener implements ActionListener {
public void actionPerformed(ActionEvent event){
LookAndFeelSelected = true;
}
}
}

This isnt a repainting issue, The look and feel goes deeper than just painting colors. Look at this tutorial http://www.roseindia.net/java/example/java/swing/GettingAndSettingLAF.shtml
below where you change your look and feel on button click change:
testFrame.getContentPane().validate();
testFrame.getContentPane().repaint();
to
SwingUtilities.updateComponentTreeUI(testFrame);

Related

Can't fix NullPointerException with JTextArea [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a text based adventure that runs in a jframe but when i run the program i get a NullPointer error on line 97 (first time i append console in the game method) and I have no idea how to fix it. I am relatively new to java so its probably something simple that I just don't know.
my code is here
package window;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Gui extends JFrame {
public JPanel contentPane;
public static JTextField input;
public static JButton send;
public static JTextArea console;
public static JTextArea invintory;
public static JTextArea stats;
static String i = "";
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public Gui() {
//variables
int Gold = 20;
int Health = 100;
int MaxHealth = 100;
//variables end
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextArea console = new JTextArea();
console.setBounds(10, 11, 281, 214);
contentPane.add(console);
input = new JTextField();
input.setBounds(10, 236, 281, 20);
contentPane.add(input);
input.setColumns(10);
JTextArea stats = new JTextArea();
stats.setBounds(301, 11, 123, 53);
contentPane.add(stats);
JTextArea invintory = new JTextArea();
invintory.setBounds(301, 75, 128, 137);
contentPane.add(invintory);
JButton send = new JButton("Send");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String i = input.getText();
input.setText("");
stats.setText("");
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
});
send.setBounds(301, 224, 128, 32);
contentPane.add(send);
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
public static void game (JButton send, JTextArea console, JTextArea stats, JTextArea invintory, JTextField input, String i) {
//start
//START
//START
//START
//START
while (true) {
console.append("You wake up open feild, with vast amounts of wheet in every direction");
console.append("There is a path going in either direction what do you want to do");
console.append("\t1. Go left.");
console.append("\t2. Go right.");
while (i == "") {
}
if (i == "1") {
console.append("1");
break;
}
else if (i == "2") {
console.append("2");
break;
}
}
//END
//END
//END
//END
}
public static void main(String[] args) {
try {
Gui frame = new Gui();
frame.setVisible(true);
Gui.game(send, console, stats, invintory, input, i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In your global variable console is null
public static JTextArea console;
You initialized it in Gui method
JTextArea console = new JTextArea();
So here in Gui method your global console variable is not initialized, This creates a local variable console under Gui method.
To initialize global variable in Gui method you need to initialize this way
console = new JTextArea();
You did this mistake to all variables so edit your code this way
public Gui() {
//variables
int Gold = 20;
int Health = 100;
int MaxHealth = 100;
//variables end
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
console = new JTextArea();
console.setBounds(10, 11, 281, 214);
contentPane.add(console);
input = new JTextField();
input.setBounds(10, 236, 281, 20);
contentPane.add(input);
input.setColumns(10);
stats = new JTextArea();
stats.setBounds(301, 11, 123, 53);
contentPane.add(stats);
invintory = new JTextArea();
invintory.setBounds(301, 75, 128, 137);
contentPane.add(invintory);
send = new JButton("Send");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String i = input.getText();
input.setText("");
stats.setText("");
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
});
send.setBounds(301, 224, 128, 32);
contentPane.add(send);
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}

Hangman actionListener graphics [duplicate]

I'm trying to create a hangman game and so far it's coming along GREAT, but the layout design just doesn't seem to fall into place! The alphabet is supposed to end up in a FlowLayout order on top of the Hangman picture with the buttons "Restart", "Help" "Add New Word" and "Exit" at the bottom! What am I doing wrong?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Hangman extends JFrame
{
int i = 0;
static JPanel panel;
static JPanel panel2;
static JPanel panel3;
public Hangman()
{
JButton[] buttons = new JButton[26];
panel = new JPanel(new FlowLayout());
panel2 = new JPanel();
panel3 = new JPanel();
JButton btnRestart = new JButton("Restart");
btnRestart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}
});
JButton btnNewWord = new JButton("Add New Word");
btnNewWord.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter fw = new FileWriter("Words.txt", true);
PrintWriter pw = new PrintWriter(fw, true);
String word = JOptionPane.showInputDialog("Please enter a word: ");
pw.println(word);
pw.close();
}
catch(IOException ie)
{
System.out.println("Error Thrown" + ie.getMessage());
}
}
});
JButton btnHelp = new JButton("Help");
btnHelp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String message = "The word to guess is represented by a row "
+ "of dashes, giving the number of letters and category of "
+ "the word. \nIf the guessing player suggests a letter "
+ "which occurs in the word, the other player writes it "
+ "in all its correct positions. \nIf the suggested "
+ "letter does not occur in the word, the other player "
+ "draws one element of the hangman diagram as a tally mark."
+ "\n"
+ "\nThe game is over when:"
+ "\nThe guessing player completes the word, or guesses "
+ "the whole word correctly"
+ "\nThe other player completes the diagram";
JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
ImageIcon icon = new ImageIcon("D:\\Varsity College\\Prog212Assign1_10-013803\\images\\Hangman1.jpg");
JLabel label = new JLabel();
label.setIcon(icon);
String b[]= {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
panel.add(buttons[i]);
}
panel2.add(label);
panel3.add(btnRestart);
panel3.add(btnNewWord);
panel3.add(btnHelp);
panel3.add(btnExit);
}
public static void main(String[] args)
{
Hangman frame = new Hangman();
frame.add(panel, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.add(panel3, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
Here are a few suggestions:
Use a GridLayout for the top panel; in this case, zero means the number of rows is determined by the specified number of columns and the total number of components in the layout:
JPanel north = new JPanel(new GridLayout(0, 9));
Here's an outline of how you can make your center panel have a reasonable initial size; note how you can draw relative to the current size:
JPanel center = new JPanel() {
private static final int N = 256;
private static final String S = "Todo...";
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int dx = (getWidth() - g.getFontMetrics().stringWidth(S)) / 2;
int dy = getHeight() / 2;
g.drawString(S, dx, dy);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(N, N);
}
};
You can construct your button names like this:
for (int i = 0; i < 26; i++) {
String letter = String.valueOf((char) (i + 'A'));
buttons[i] = new JButton(letter);
north.add(buttons[i]);
}
Make your panels instance variables and start on the event dispatch thread:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Hangman frame = new Hangman();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(frame.north, BorderLayout.NORTH);
frame.add(frame.center, BorderLayout.CENTER);
frame.add(frame.south, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
This problem is pretty well documented if you do some research - it seems all the panels (besides the CENTER one) aren't recalculated when resized. See How do I make this FlowLayout wrap within its JSplitPane? and http://www.velocityreviews.com/forums/t608472-wrap-flowlayout.html
But for a really quick fix, try changing your main method to this... (basically using a BoxLayout as your main container)
public static void main(String[] args)
{
TempProject frame = new TempProject();
Box mainPanel = Box.createVerticalBox();
frame.setContentPane(mainPanel);
mainPanel.add(panel);
mainPanel.add(panel2);
mainPanel.add(panel3);
frame.pack();
frame.setVisible(true);
}

java parsing data from component

I am creating a game, and I am doing a character selection screen which has a JTextField for entering the user name, the screen also has a JButton "Create Character", which, when pressed will parse the JTextField and if any problems(space in name, begin with space, etc..) it will put some text to a JLabel next to the JTextField.
I hook up the JButton to an actionPerformed method, which calls a function that parses the data. My problem is that every time I press the button, a new label is being placed on top of the original JLabel.
I create the JLabel like this:
public static JLabel label;
label = new JLabel();
// some properties
And I call the parsing method like so:
parseCharacterSelection(nameInput, label);
where nameInput is the JTextField.
My question is, why is there a new Label being created every time I press the JButton
public void parseCharacterCreation(JTextField input, JLabel label) {
// Variable that hold whether or not
// the User Name is acceptable
player_name = input.getText();
// Make some initial checks on the
// input string
//----------------------------------
if( player_name.isEmpty() ) {
label.setText("You need to pick a username");
} else if( player_name.startsWith(" ") ) {
label.setText("Name Cannot start with a space");
} else {
pass = true;
}
// Attempt to write to file
// Catch some errors
//----------------------------------
if(pass == true) {
try {
if( player_name.contains(" ") ) {
player_name = player_name.replaceAll("\\s", "_");
player_file = new File("src/Resources/characters/" + player_name + ".properties");
}
if(!player_file.exists()) {
player_file.createNewFile();
}
FileWriter fw = new FileWriter(player_file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(player_name);
bw.close();
} catch( IOException e ) {
e.printStackTrace();
} finally {
System.out.println("DONE");
}
}
}
// ScreenCharacter Class
public class ScreenCharacter extends JPanel {
public static JButton create;
public static JTextField nameInput;
public static JLabel errorLabel;
public ScreenCharacter() {
this.setLayout(null);
this.add(createUserName());
this.add(createMainArea());
}
private static JPanel createUserName() {
MatteBorder matteBorder = new MatteBorder(1, 0, 1, 0, Color.decode("#222222"));
EmptyBorder emptyBorder = new EmptyBorder(10, 75, 10, 10);
CompoundBorder border = new CompoundBorder(matteBorder, emptyBorder);
JPanel userNameArea = new JPanel();
userNameArea.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
userNameArea.setBounds(0, 35, Engine.screenX, 50);
userNameArea.setBorder(border);
userNameArea.setBackground(new Color(255, 255, 255, 70));
JLabel nameLabel = new JLabel();
nameLabel.setText("Enter Your Username: ");
nameInput = new JTextField();
nameInput.setForeground(Color.black);
nameInput.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
nameInput.setPreferredSize(new Dimension(200, 25));
errorLabel = new JLabel();
errorLabel.setText("This is a test label");
errorLabel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
errorLabel.setPreferredSize(new Dimension(200, 25));
errorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
userNameArea.add(nameLabel);
userNameArea.add(nameInput);
userNameArea.add(errorLabel);
return userNameArea;
}
private static JPanel createMainArea() {
JPanel resetCreatePanel = new JPanel(new GridLayout(1, 2));
resetCreatePanel.setPreferredSize(new Dimension(300, 30));
resetCreatePanel.setBackground(Color.black);
create = new JButton("Create Character");
create.setBorder(BorderFactory.createLineBorder(Color.decode("#171717")));
create.setFont(new Font("Dialog", 1, 11));
create.setBackground(Color.black);
create.setForeground(Color.white);
create.setFocusPainted(false);
create.setContentAreaFilled(false);
create.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(!errorLabel.getText().isEmpty()) {
errorLabel.setText("");
} else {
Engine.p_parser.parseCharacterCreation(nameInput, errorLabel);
}
}
});
resetCreatePanel.add(create);
}
}
// Engine
public class Engine {
public static PlayerParser p_parser;
public Engine() {
p_parser = new PlayerParser();
}
}
Thanks everyone for the help. The "problem" was that the JPanel that the components were sitting on had a semi-transparent background. And JComponents with transparency get messed up somehow, which made it appear like there are multiple labels being created. But it works fine without transparency.

Beginner Scoring program button development in Java

I'm trying to add a "green team" to an example scoring GUI I found online. For some reason, the code compiles, but it runs with only the original two teams. I've tried playing around with the sizes/locations somewhat clumsily, and since no change was observed with these modications (NO change at ALL), I admit that I must be missing some necessary property or something. Any help? Here's the code:
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonDemo_Extended3 implements ActionListener{
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
int greenScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;
JButton redButton, blueButton, greenButton,resetButton;
public JPanel createContentPane (){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(0, 0);
titlePanel.setSize(500, 500);
totalGUI.add(titlePanel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(300, 0);
redLabel.setSize(100, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(900, 0);
blueLabel.setSize(100, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(600, 0);
greenLabel.setSize(100, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(500, 30);
totalGUI.add(scorePanel);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(40, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(60, 0);
greenScore.setSize(40, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
blueScore = new JLabel(""+blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(40, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(2600, 70);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(30, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(150, 0);
blueButton.setSize(30, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
greenButton = new JButton("Green Score!");
greenButton.setLocation(250, 0);
greenButton.setSize(30, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 100);
resetButton.setSize(50, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == redButton)
{
redScoreAmount = redScoreAmount + 1;
redScore.setText(""+redScoreAmount);
}
else if(e.getSource() == blueButton)
{
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText(""+blueScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
redScoreAmount = 0;
blueScoreAmount = 0;
greenScoreAmount = 0;
redScore.setText(""+redScoreAmount);
blueScore.setText(""+blueScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended demo = new ButtonDemo_Extended();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
import javax.swing.*;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonDemo_Extended3 implements ActionListener{
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
int greenScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;
JButton redButton, blueButton, greenButton,resetButton;
public JPanel createContentPane (){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.setLocation(0, 0);
titlePanel.setSize(500, 500);
redLabel = new JLabel("Red Team");
redLabel.setLocation(300, 0);
redLabel.setSize(100, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel, 0 );
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(900, 0);
blueLabel.setSize(100, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel, 1);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(600, 0);
greenLabel.setSize(100, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(500, 30);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(40, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(60, 0);
greenScore.setSize(40, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
blueScore = new JLabel(""+blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(40, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(2600, 70);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(30, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(150, 0);
blueButton.setSize(30, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
greenButton = new JButton("Green Score!");
greenButton.setLocation(250, 0);
greenButton.setSize(30, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 100);
resetButton.setSize(50, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
totalGUI.add(buttonPanel);
totalGUI.add(scorePanel);
totalGUI.add(titlePanel);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == redButton)
{
redScoreAmount = redScoreAmount + 1;
redScore.setText(""+redScoreAmount);
}
else if(e.getSource() == blueButton)
{
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText(""+blueScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
redScoreAmount = 0;
blueScoreAmount = 0;
greenScoreAmount = 0;
redScore.setText(""+redScoreAmount);
blueScore.setText(""+blueScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended3 demo = new ButtonDemo_Extended3();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You have to use a layout manager in order to display your widgets. In this case I used a FlowLayout(). Also, make sure that you add the elements first in the panel and then you add the panel to its parent panel.
Now, the code works as you probably want, but again you should use a particular layout in order to arrange the panels inside the frame.
If I run your code unmodified, I see just the "Red Team" label, and some buttons which are too small to read the text (and some of them only appear when moused over).
If you comment out all the null layouts:
//buttonPanel.setLayout(null);
then all three buttons and labels appear properly.
Doing without a layout manager, and using absolute positioning, is possible (see the Java Swing tutorial page on this exact topic) but not usually recommended. There is a lot of information on using layout managers in the Laying Out Components Within a Container lesson of the Swing tutorials.

Add components to JDialog

When I run this, an empty title bar is displayed. I just want to be able to see the components and work from there, but nothing is displayed. The dialog is designed to allow the user to select a color by moving sliders, then return to color to the main page.
import java.awt.*;
import javax.swing.*;
public class ColourDialog extends JDialog
{
String colorNames[] = {"Red: ", "Green: ", "Blue: "};
Label labels[] = new Label[3];
JSlider slider[]= new JSlider[3];
Label lb;
static ColourDialog d;
public void ColourDialog()
{
setModal(true);
Container c = getContentPane();
c.setLayout(new BorderLayout());
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(0, 1));
for (int i = 0; i < slider.length; i++)
{
labels[i] = new Label(colorNames[i] + 255);
sliderPanel.add(labels[i]);
slider[i] = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
slider[i].setMinorTickSpacing(10);
slider[i].setMajorTickSpacing(50);
slider[i].setPaintTicks(true);
slider[i].setPaintLabels(true);
sliderPanel.add(slider[i]);
//slider[i].addChangeListener(this);
}
lb = new Label("Colour");
c.add(sliderPanel, BorderLayout.CENTER);
c.add(lb, BorderLayout.SOUTH);
setSize(500, 450);
setLocation(200,200);
setTitle("Colour Dialog");
}
public static Color showDialog()
{
if (d == null)
d = new ColourDialog();
d.show();
//return new Color(red,green,blue);
return new Color(0,0,0);
}
public static void main(String args[])
{
ColourDialog.showDialog();
}
}
I think that you have look at JColorChooser, this JComponent can returns selected Color
there I can't fout out correct definitions and initializations for JSlider
EDIT
there are lots of mistakes starting with extends JDialog end with public static Color showDialog(), that returns empty container typos with initializations for ColourDialog()
import java.awt.*;
import javax.swing.*;
public class ColourDialog {
private JDialog dialog = new JDialog();
private String colorNames[] = {"Red: ", "Green: ", "Blue: "};
private Label labels[] = new Label[3];
private JSlider slider[] = new JSlider[3];
private Label lb;
public ColourDialog() {
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(0, 1));
for (int i = 0; i < slider.length; i++) {
labels[i] = new Label(colorNames[i] + 255);
sliderPanel.add(labels[i]);
slider[i] = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
slider[i].setMinorTickSpacing(10);
slider[i].setMajorTickSpacing(50);
slider[i].setPaintTicks(true);
slider[i].setPaintLabels(true);
sliderPanel.add(slider[i]);
}
lb = new Label("Colour");
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setModal(true);
dialog.add(sliderPanel, BorderLayout.CENTER);
dialog.add(lb, BorderLayout.SOUTH);
dialog.pack();
dialog.setLocation(200, 200);
dialog.setTitle("Colour Dialog");
dialog.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ColourDialog colourDialog = new ColourDialog();
}
});
}
}
I think it might be because you say "public void ColourDialog()" this is an invalid constructor. Try getting rid of the "void" and try again.
You never call the method ColorDialog(). This is a good spot to mention "start methods with a lower case letter). To fix you code:
Change:
d = new ColourDialog();
To:
d = new ColourDialog();
d.ColourDialog();

Categories