Basiclly I got 2 calsses, SSPUserInput and SSPViewer.
I want to press a button in SSPUserInput class and change a JLabel name in SSPViewer. It's basically a rock paper scissor game. This is my first time posting here, I'm sorry if I've done something wrong.
package p3;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SSPUserInput extends JPanel implements ActionListener {
private JPanel panel = new JPanel();
private JButton btnRock = new JButton ("Rock");
private JButton btnScissor = new JButton ("Scissor");
private JButton btnPaper = new JButton ("Paper");
private JButton btnNewGame = new JButton ("New game");
private JButton btnQuit = new JButton ("Quit");
private Font plainSS14 = new Font("SansSerif", Font.PLAIN, 14);
private SSPViewer lblHumanChoice;
private String rock;
private int scissor;
private int paper;
public SSPUserInput(SSPViewer lblHumanChoice) {
this.lblHumanChoice = lblHumanChoice;
}
public SSPUserInput(){
setPreferredSize (new Dimension(400, 200));
setLayout( null);
btnRock.setBounds(20, 50, 100, 35);
btnRock.setFont(plainSS14);
btnRock.addActionListener(this);
btnScissor.setBounds(155, 50, 100, 35);
btnScissor.setFont(plainSS14);
btnScissor.addActionListener(this);
btnPaper.setBounds(290, 50, 100, 35);
btnPaper.setFont(plainSS14);
btnPaper.addActionListener(this);
btnNewGame.setBounds(20, 100, 370, 35);
btnNewGame.setFont(plainSS14);
btnNewGame.addActionListener(this);
btnQuit.setBounds(20, 150, 370, 35);
btnQuit.setFont(plainSS14);
btnQuit.addActionListener(this);
add(btnRock);
add(btnScissor);
add(btnPaper);
add(btnNewGame);
add(btnQuit);
}
// public String getRock() {
// return rock;
// }
public void actionPerformed(ActionEvent e) {
if( e.getSource() == btnRock ) {
JOptionPane.showMessageDialog(null, "Hello world!");
}
else if( e.getSource() == btnScissor){
}
else if( e.getSource() == btnPaper){
}
else if( e.getSource() == btnNewGame){
}
}
}
package p3;
import java.awt.*;
import javax.swing.*;
public class SSPViewer extends JPanel {
private JLabel lblFirst = new JLabel("First to 3!");
private JLabel lblHuman = new JLabel("Human");
private JLabel lblComputer = new JLabel("Computer");
private JLabel lblHumanChoice = new JLabel();
private JLabel lblComputerChoice = new JLabel();
private JLabel lblHumanPoints = new JLabel("0");
private JLabel lblComputerPoints = new JLabel("0");
private SSPUserInput rock;
private SSPUserInput scissor;
private SSPUserInput paper;
public SSPViewer(SSPUserInput rock, SSPUserInput scissor, SSPUserInput paper) {
this.rock = rock;
this.scissor = scissor;
this.paper = paper;
}
public SSPViewer() {
setLayout(null);
setPreferredSize(new Dimension(400, 200));
lblFirst.setBounds(140, 10, 210, 24);
lblFirst.setFont(new Font("Arial", 2, 24));
lblHuman.setBounds(100, 75, 210, 17);
lblHuman.setFont(new Font("Arial", 2, 17));
lblComputer.setBounds(250, 75, 210, 17);
lblComputer.setFont(new Font("Arial", 2, 17));
lblHumanPoints.setBounds(120, 95, 210, 17);
lblHumanPoints.setFont(new Font("Arial", 2, 17));
lblComputerPoints.setBounds(280, 95, 210, 17);
lblComputerPoints.setFont(new Font("Arial", 2, 17));
lblHumanChoice.setBounds(100, 115, 210, 17);
lblHumanChoice.setFont(new Font("Arial", 2, 17));
// lblHuman.setText(rock.getRock());
lblComputerChoice.setBounds(260, 115, 210, 17);
lblComputerChoice.setFont(new Font("Arial", 2, 17));
add(lblFirst);
add(lblHuman);
add(lblComputer);
add(lblHumanPoints);
add(lblComputerPoints);
add(lblHumanChoice);
add(lblComputerChoice);
}
public JLabel getLblHumanChoice() {
return lblHumanChoice;
}
}
package p3;
import javax.swing.*;
public class SSPApp {
public static void main( String[] args ) {
SSPPlayer player = new SSPPlayer();
SSPViewer viewer = new SSPViewer();
SSPController controller = new SSPController();
SSPUserInput userInput = new SSPUserInput();
JFrame frame1 = new JFrame( "SSPViewer" );
frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame1.add( viewer );
frame1.pack();
frame1.setVisible( true );
JFrame frame2 = new JFrame( "SSPUserInput" );
frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame2.add( userInput );
frame2.pack();
frame2.setVisible( true );
}
}
Basically you need to hold a reference to the 'view' on the 'userInput'. And you already have it.
public ExampleFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridLayout(2, 1));
setContentPane(contentPane);
// create a view
SSPViewer sspViewer = new SSPViewer();
contentPane.add(sspViewer);
// pass a reference to the userInput
contentPane.add(new SSPUserInput(sspViewer));
}
on the viewer class, you need to add a method to access the local private components, for example im going to change a text of JLabel :
public class SSPViewer extends JPanel {
// code ...
// setter. lblHuman is a reference here in that class
// to the view class, so all public members are available
public void setTextExample (String s){
this.lblHuman.setText(s);
}
}
Then on the userInput class, you can 'refer' to that property on the other JPanel :
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnRock) {
JOptionPane.showMessageDialog(null, "Hello world!");
// accessible now
lblHumanChoice.setTextExample("changed from other panel");
} else ...
}
NOTE: I edited the answer.
I've added the codes here. This way when you press ROCK button(for example), it shows its name in the other window. I used JFrame and called the SSPViewer class inside of SSPUserInput class. NOTE: I think you want to call some other classes inside SSPApp(that's why I wrote it) but even if you run SSPUserInput, it still pops up two windows.Now they are somethings like that: enter image description here and like this
SSPUserInput class
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SSPUserInput extends JFrame {
private JPanel contentPane;
JButton PaperButton;
JButton ScissorButton;
JButton rockButton;
SSPViewer viewer = new SSPViewer();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSPUserInput frame = new SSPUserInput();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SSPUserInput() {
viewer.frame.setVisible(true); //this code is important
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 93, 9, 19, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
rockButton = new JButton("ROCK");
GridBagConstraints gbc_rockButton = new GridBagConstraints();
gbc_rockButton.fill = GridBagConstraints.HORIZONTAL;
gbc_rockButton.insets = new Insets(0, 0, 5, 5);
gbc_rockButton.gridx = 1;
gbc_rockButton.gridy = 3;
panel.add(rockButton, gbc_rockButton);
ScissorButton = new JButton("Scissor");
GridBagConstraints gbc_ScissorButton = new GridBagConstraints();
gbc_ScissorButton.fill = GridBagConstraints.BOTH;
gbc_ScissorButton.insets = new Insets(0, 0, 5, 5);
gbc_ScissorButton.gridx = 3;
gbc_ScissorButton.gridy = 3;
panel.add(ScissorButton, gbc_ScissorButton);
PaperButton = new JButton("PAPER");
GridBagConstraints gbc_PaperButton = new GridBagConstraints();
gbc_PaperButton.fill = GridBagConstraints.HORIZONTAL;
gbc_PaperButton.insets = new Insets(0, 0, 5, 0);
gbc_PaperButton.gridx = 5;
gbc_PaperButton.gridy = 3;
panel.add(PaperButton, gbc_PaperButton);
JButton btnNewGame = new JButton("New Game");
GridBagConstraints gbc_btnNewGame = new GridBagConstraints();
gbc_btnNewGame.fill = GridBagConstraints.HORIZONTAL;
gbc_btnNewGame.insets = new Insets(0, 0, 5, 5);
gbc_btnNewGame.gridx = 3;
gbc_btnNewGame.gridy = 5;
panel.add(btnNewGame, gbc_btnNewGame);
JButton btnQuit = new JButton("Quit");
GridBagConstraints gbc_btnQuit = new GridBagConstraints();
gbc_btnQuit.fill = GridBagConstraints.HORIZONTAL;
gbc_btnQuit.insets = new Insets(0, 0, 0, 5);
gbc_btnQuit.gridx = 3;
gbc_btnQuit.gridy = 6;
panel.add(btnQuit, gbc_btnQuit);
MyListener2 listener = new MyListener2();
rockButton.addActionListener(listener);
ScissorButton.addActionListener(listener);
PaperButton.addActionListener(listener);
}
private class MyListener2 implements ActionListener {
public void mousePressed(ActionEvent e) {
//System.out.println(((JButton) e.getSource()).getText());
//String name = ((JButton) e.getSource()).getText();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println(((JButton) arg0.getSource()).getText());
String name = ((JButton) arg0.getSource()).getText();
viewer.humanWin.setText(name);
}
}
}
SSPViewer class
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Insets;
public class SSPViewer {
JFrame frame;
JLabel humanWin;
JLabel computerWin;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSPViewer window = new SSPViewer();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SSPViewer() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 4, 0, 0, 0, 0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblFirstTo = new JLabel("First to 3!");
GridBagConstraints gbc_lblFirstTo = new GridBagConstraints();
gbc_lblFirstTo.insets = new Insets(0, 0, 5, 5);
gbc_lblFirstTo.gridx = 5;
gbc_lblFirstTo.gridy = 2;
panel.add(lblFirstTo, gbc_lblFirstTo);
JLabel lblHuman = new JLabel("Human");
GridBagConstraints gbc_lblHuman = new GridBagConstraints();
gbc_lblHuman.gridwidth = 3;
gbc_lblHuman.insets = new Insets(0, 0, 5, 5);
gbc_lblHuman.gridx = 2;
gbc_lblHuman.gridy = 4;
panel.add(lblHuman, gbc_lblHuman);
JLabel lblComputer = new JLabel("Computer");
GridBagConstraints gbc_lblComputer = new GridBagConstraints();
gbc_lblComputer.insets = new Insets(0, 0, 5, 0);
gbc_lblComputer.gridx = 7;
gbc_lblComputer.gridy = 4;
panel.add(lblComputer, gbc_lblComputer);
humanWin = new JLabel("");
GridBagConstraints gbc_humanWin = new GridBagConstraints();
gbc_humanWin.insets = new Insets(0, 0, 0, 5);
gbc_humanWin.gridx = 3;
gbc_humanWin.gridy = 6;
panel.add(humanWin, gbc_humanWin);
computerWin = new JLabel("");
GridBagConstraints gbc_computerWin = new GridBagConstraints();
gbc_computerWin.gridx = 7;
gbc_computerWin.gridy = 6;
panel.add(computerWin, gbc_computerWin);
}
}
SSPApp class
public class SSPApp {
SSPUserInput s = new SSPUserInput();
}
Related
I'm making a program in Java Swing and so far I only have the GUI done but that's what's giving me the problem. I have no idea why, but when my "tasks" method is activated using the button, the JComponents that are supposed to show are not shown properly. The JPanel "tasks" is supposed to be 300x300 but it doesn't look like that unless the window is minimized and reopened. The sizes are wrong and some of the JLabels are cut off too. I don't know what to do, I've tried rearranging the code so that the main GUI frame is made visible after, but that didn't work either. I've been trying to solve this problem for so long. What should I do?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDate;
import java.util.Date;
public class gui implements ActionListener {
static JFrame frame;
Container container;
JPanel title, open, choicePanel, date, tasks, ttitle, ntes;
JLabel titleName, date1, ttitle2, rmndAt, ntes1;
Font titleFont = new Font("Lucida Handwriting", Font.PLAIN, 70);
Font clickHereFont = new Font("Lucida Handwriting", Font.PLAIN, 18);
Font stitleFont = new Font("Lucida Handwriting", Font.PLAIN, 50);
JButton openButton, tasksButton, notesButton, adtButton, tnButton;
Date datee = new Date(); //date object
{
frame = new JFrame();
frame.setSize(1000,700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); d
frame.getContentPane().setBackground(new Color(4, 102, 69));
frame.setResizable(false);
frame.setLayout(null);
date = new JPanel();
date.setBounds(350,150,300,200);
date.setBackground(new Color(14, 21, 7));
date1 = new JLabel("Today is "+ (LocalDate.now()).toString() + " ");
date1.setForeground(new Color(135, 233, 169));
date1.setFont(clickHereFont);
title = new JPanel();
title.setBounds(170,250,650,120);
title.setBackground(new Color(135, 233, 169));
titleName = new JLabel("Daily Planner");
titleName.setForeground(new Color(14, 21, 7));
titleName.setFont(titleFont);
open = new JPanel();
open.setBounds(400,420,150,75);
open.setBackground(new Color(4, 102, 69));
openButton = new JButton("CLICK HERE");
openButton.setBounds(300,420,200,100);
openButton.setBackground(new Color(14, 21, 7));
openButton.setForeground(new Color(135, 233, 169));
openButton.setFont(clickHereFont);
openButton.addActionListener(this);
date.add(date1);
frame.add(date);
title.add(titleName);
frame.add(title);
frame.add(open);
open.add(openButton);
frame.setVisible(true);
}
public static void main(String[] args) {
new gui();
}
public gui() {
}
public void choice() {
title.setVisible(false);
open.setVisible(false);
date.setVisible(false);
choicePanel = new JPanel();
choicePanel.setBounds(160,100,650,500);
choicePanel.setBackground(new Color(135, 233, 169));
choicePanel.setLayout(new GridLayout(1,2));
tasksButton = new JButton("TASKS");
tasksButton.setBackground(new Color (6, 122, 82));
tasksButton.setFont(titleFont); //reused the "titleFont" font
tasksButton.setForeground(Color.white);
tasksButton.addActionListener(this);
notesButton = new JButton("NOTES");
notesButton.setBackground(new Color(63, 194, 131));
notesButton.setFont(titleFont);
notesButton.setForeground(Color.white);
notesButton.addActionListener(this);
choicePanel.add(tasksButton);
choicePanel.add(notesButton);
frame.add(choicePanel);
}
public void tasks() {
choicePanel.setVisible(false);
tasks = new JPanel();
tasks.setBounds(30,150,300,300);
tasks.setBackground(new Color(6, 122, 76));
ttitle = new JPanel();
ttitle.setBackground(new Color(4, 102, 69));
ttitle.setBounds(20,50,500,100);
ttitle2 = new JLabel("TASKS");
ttitle2.setBounds(50,50,150,45);
ttitle2.setBackground(new Color(4, 102, 69));
ttitle2.setForeground(Color.white);
ttitle2.setFont(stitleFont);
adtButton = new JButton("+");
adtButton.setBounds(550,50,80,80);
adtButton.setBackground(new Color(4, 102, 69));
adtButton.setForeground(Color.white);
adtButton.setFont(stitleFont);
rmndAt = new JLabel("REMIND AT");
rmndAt.setBounds(750,50,200,95);
rmndAt.setBackground(new Color(4, 102, 69));
rmndAt.setForeground(Color.white);
rmndAt.setFont(clickHereFont);
frame.add(tasks);
ttitle.add(ttitle2);
frame.add(ttitle);
frame.add(adtButton);
frame.add(rmndAt);
}
public void ntess() {
choicePanel.setVisible(false);
title.setVisible(false);
ntes = new JPanel();
ntes.setBackground(new Color(6, 122, 76));
ntes.setBounds(30,150,200,200);
frame.add(ntes);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
choice();
}
else if (e.getSource()==notesButton) {
ntess();
}
else if (e.getSource() == tasksButton) {
tasks();
}
}
}
I just want an answer and want to make this program work
Be very careful what you wish for...
The following makes use of the following concepts...
Creating a GUI With Swing
Laying Out Components Within a Container* How to Use CardLayout
Dependency Injection in Java
Observer Pattern
The example is also incomplete and you're going to need to take the time to understand the above concepts in order to fill out the missing parts
I also think you're going to want to have a look at How to Use Tables at some point.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new NavigationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class Support {
public static final Font TITLE_FONT = new Font("Lucida Handwriting", Font.PLAIN, 70);
public static final Font NORMAL_FONT = new Font("Lucida Handwriting", Font.PLAIN, 18);
public static final Font SMALL_FONT = new Font("Lucida Handwriting", Font.PLAIN, 18);
}
public class NavigationPane extends JPanel {
protected enum View {
MAIN, CHOICE, NOTES, TASKS;
}
private CardLayout cardLayout;
public NavigationPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
add(new MainPane(new MainPane.Observer() {
#Override
public void navigateToChoices(MainPane source) {
navigateTo(View.CHOICE);
}
}), View.MAIN);
add(new ChoicePane(new ChoicePane.Observer() {
#Override
public void navigateToTasks(ChoicePane source) {
navigateTo(View.TASKS);
}
#Override
public void navigateToNotes(ChoicePane source) {
navigateTo(View.NOTES);
}
}), View.CHOICE);
add(new TasksPane(), View.TASKS);
add(new NotesPane(), View.NOTES);
navigateTo(View.MAIN);
}
protected void navigateTo(View view) {
cardLayout.show(this, view.name());
}
// Because I'm lazy
protected void add(Component comp, View view) {
super.add(comp, view.name());
}
}
public class MainPane extends JPanel {
public interface Observer {
public void navigateToChoices(MainPane source);
}
private Observer observer;
public MainPane(Observer observer) {
this.observer = observer;
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(new Color(4, 102, 69));
setLayout(new GridBagLayout());
JLabel todayLabel = new JLabel("Today is " + DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.now()));
todayLabel.setFont(Support.NORMAL_FONT);
todayLabel.setForeground(new Color(135, 233, 169));
todayLabel.setBackground(new Color(14, 21, 7));
todayLabel.setOpaque(true);
todayLabel.setBorder(new EmptyBorder(16, 16, 16, 16));
JLabel titleLabel = new JLabel("Daily Planner");
titleLabel.setFont(Support.TITLE_FONT);
titleLabel.setBackground(new Color(135, 233, 169));
titleLabel.setOpaque(true);
titleLabel.setBorder(new EmptyBorder(32, 32, 32, 32));
JButton clickHereButton = new JButton("Click Here");
clickHereButton.setFont(Support.SMALL_FONT);
clickHereButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.navigateToChoices(MainPane.this);
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.gridwidth = gbc.REMAINDER;
gbc.insets = new Insets(8, 8, 32, 8);
add(todayLabel, gbc);
gbc.gridy++;
gbc.insets = new Insets(0, 8, 32, 8);
add(titleLabel, gbc);
gbc.gridy++;
gbc.insets = new Insets(0, 8, 8, 8);
add(clickHereButton, gbc);
}
}
public class ChoicePane extends JPanel {
public interface Observer {
public void navigateToTasks(ChoicePane source);
public void navigateToNotes(ChoicePane source);
}
private Observer observer;
public ChoicePane(Observer observer) {
this.observer = observer;
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(new Color(4, 102, 69));
setLayout(new GridLayout(1, 2, 8, 8));
JButton tasksButton = new JButton("TASKS");
tasksButton.setOpaque(true);
tasksButton.setBorderPainted(false);
tasksButton.setBackground(new Color(63, 194, 131));
tasksButton.setFont(Support.TITLE_FONT); //reused the "titleFont" font
tasksButton.setForeground(Color.white);
tasksButton.setFocusPainted(false);
tasksButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.navigateToTasks(ChoicePane.this);
}
});
JButton notesButton = new JButton("NOTES");
notesButton.setOpaque(true);
notesButton.setBorderPainted(false);
notesButton.setBackground(new Color(63, 194, 131));
notesButton.setFont(Support.TITLE_FONT);
notesButton.setForeground(Color.white);
notesButton.setFocusPainted(false);
notesButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.navigateToNotes(ChoicePane.this);
}
});
add(tasksButton);
add(notesButton);
}
}
public class TasksPane extends JPanel {
public TasksPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(new Color(4, 102, 69));
setLayout(new BorderLayout(8, 8));
JPanel titlePane = new JPanel(new GridBagLayout());
titlePane.setOpaque(false);
JLabel titleLabel = new JLabel("Tasks");
titleLabel.setBackground(new Color(4, 102, 69));
titleLabel.setForeground(Color.WHITE);
titleLabel.setFont(Support.SMALL_FONT);
JButton addButton = new JButton("+");
addButton.setBorderPainted(false);
addButton.setFocusPainted(false);
addButton.setBackground(new Color(63, 194, 131));
addButton.setForeground(Color.white);
addButton.setFont(Support.SMALL_FONT);
addButton.setOpaque(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = gbc.LINE_START;
titlePane.add(titleLabel, gbc);
gbc.weightx = 0;
gbc.gridx++;
titlePane.add(addButton, gbc);
add(titlePane, BorderLayout.NORTH);
// Personally, I think you need a JTable
JPanel fillerPane = new JPanel();
fillerPane.setBackground(new Color(6, 122, 76));
add(fillerPane);
}
}
public class NotesPane extends JPanel {
public NotesPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(new Color(4, 102, 69));
setLayout(new BorderLayout(8, 8));
JPanel titlePane = new JPanel(new GridBagLayout());
titlePane.setOpaque(false);
JLabel titleLabel = new JLabel("Notes");
titleLabel.setBackground(new Color(4, 102, 69));
titleLabel.setForeground(Color.WHITE);
titleLabel.setFont(Support.SMALL_FONT);
JButton addButton = new JButton("+");
addButton.setBorderPainted(false);
addButton.setFocusPainted(false);
addButton.setBackground(new Color(63, 194, 131));
addButton.setForeground(Color.white);
addButton.setFont(Support.SMALL_FONT);
addButton.setOpaque(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = gbc.LINE_START;
titlePane.add(titleLabel, gbc);
gbc.weightx = 0;
gbc.gridx++;
titlePane.add(addButton, gbc);
add(titlePane, BorderLayout.NORTH);
// Personally, I think you need a JTable
JPanel fillerPane = new JPanel();
fillerPane.setBackground(new Color(6, 122, 76));
add(fillerPane);
}
}
}
Side by comparison of your output (left) and mine (right)
Beside also getting reusability for free, imagine your client comes back and says, "I want to change the font" or even worse, "I just want to change the font on these few elements".
Which approach do you think will cope better?
Or, you get some user like me, whose blind as a bat and has the font accessibility of the system ramped right up?
I'm following the previous suggestion of adopting a JList and calling setVisibleRowCount() in my JDialog.
I tried to restrict the number of rows to 2; however the dialog is packed into a big, unscrolled JList. I expected it would show only 2 rows and the rest would be reached through scrolling, leaving space for a future third element in the design (the orders list).
Please take a look at the SSCCE.
TestDialog.java
package testdialog;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestDialog {
private static void createAndShowGUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new JDViewCustomer(frame, true).setVisible(true);
}
});
frame.getContentPane().add(button, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
CustomerAddress.java
package testdialog;
public class CustomerAddress {
private final String title;
public CustomerAddress(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
JDViewCustomer.java
package testdialog;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JDViewCustomer extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private final JPanel jPanelCustomerInfo;
private final JPanel jPanelCustomerAddresses;
private final JPanel jPanelCustomerOrders;
private JTextField txtarea_1;
private JPanel panelNomeDoCliente;
private JPanel panelDadosDoCliente;
private JPanel panelAbaixoDeCustomerAddresses;
private JPanel panelTituloEnderecos;
private JPanel panelContendoOsEnderecos;
private JLabel lblEnderecos;
private JPanel panel;
private JScrollPane scrollPane;
private JList<CustomerAddress> jListCustomerAddresses;
public JDViewCustomer(java.awt.Frame parent, boolean modal) {
super(parent, modal);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
panel = new JPanel();
getContentPane().add(panel);
/*scrollPane = new JScrollPane(panel);
getContentPane().add(scrollPane);*/
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
jPanelCustomerInfo = new JPanel();
panel.add(jPanelCustomerInfo);
jPanelCustomerInfo.setBackground(new Color(255, 255, 255));
jPanelCustomerInfo.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
jPanelCustomerInfo.setLayout(new BoxLayout(jPanelCustomerInfo, BoxLayout.Y_AXIS));
panelNomeDoCliente = new JPanel();
panelNomeDoCliente.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelNomeDoCliente.setBackground(Color.LIGHT_GRAY);
jPanelCustomerInfo.add(panelNomeDoCliente);
GridBagLayout gbl_panelNomeDoCliente = new GridBagLayout();
gbl_panelNomeDoCliente.columnWidths = new int[]{73, 376, 45, 53, 0};
gbl_panelNomeDoCliente.rowHeights = new int[]{31, 0};
gbl_panelNomeDoCliente.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelNomeDoCliente.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panelNomeDoCliente.setLayout(gbl_panelNomeDoCliente);
panelDadosDoCliente = new JPanel();
panelDadosDoCliente.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelDadosDoCliente.setBackground(Color.WHITE);
jPanelCustomerInfo.add(panelDadosDoCliente);
GridBagLayout gbl_panelDadosDoCliente = new GridBagLayout();
gbl_panelDadosDoCliente.columnWidths = new int[]{58, 199, 38, 102, 27, 123, 0};
gbl_panelDadosDoCliente.rowHeights = new int[]{0, 14, 0};
gbl_panelDadosDoCliente.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelDadosDoCliente.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelDadosDoCliente.setLayout(gbl_panelDadosDoCliente);
jPanelCustomerAddresses = new JPanel();
scrollPane = new JScrollPane(jPanelCustomerAddresses);
getContentPane().add(scrollPane);
//panel.add(jPanelCustomerAddresses);
jPanelCustomerAddresses.setBackground(new Color(255, 255, 255));
jPanelCustomerAddresses.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
jPanelCustomerAddresses.setLayout(new BoxLayout(jPanelCustomerAddresses, BoxLayout.Y_AXIS));
panelAbaixoDeCustomerAddresses = new JPanel();
panelAbaixoDeCustomerAddresses.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
jPanelCustomerAddresses.add(panelAbaixoDeCustomerAddresses);
panelAbaixoDeCustomerAddresses.setLayout(new BoxLayout(panelAbaixoDeCustomerAddresses, BoxLayout.Y_AXIS));
panelTituloEnderecos = new JPanel();
panelTituloEnderecos.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
FlowLayout fl_panelTituloEnderecos = (FlowLayout) panelTituloEnderecos.getLayout();
fl_panelTituloEnderecos.setAlignment(FlowLayout.LEFT);
panelTituloEnderecos.setBackground(Color.LIGHT_GRAY);
panelAbaixoDeCustomerAddresses.add(panelTituloEnderecos);
lblEnderecos = new JLabel("Endereço");
panelTituloEnderecos.add(lblEnderecos);
panelContendoOsEnderecos = new JPanel();
panelContendoOsEnderecos.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelContendoOsEnderecos.setBackground(Color.WHITE);
panelAbaixoDeCustomerAddresses.add(panelContendoOsEnderecos);
panelContendoOsEnderecos.setLayout(new BoxLayout(panelContendoOsEnderecos, BoxLayout.Y_AXIS));
jPanelCustomerOrders = new JPanel();
panel.add(jPanelCustomerOrders);
txtarea_1 = new JTextField();
txtarea_1.setText("Área 3");
jPanelCustomerOrders.add(txtarea_1);
txtarea_1.setColumns(10);
initComponents();
pack();
setLocationRelativeTo(parent);
LoadCustomerDataWorker worker = new LoadCustomerDataWorker(this);
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
singleThreadPool.execute(worker);
}
public void addCustomerAddresses(List<CustomerAddress> customerAddresses) {
Objects.requireNonNull(customerAddresses);
DefaultListModel<CustomerAddress> listModel = new DefaultListModel<>();
for (CustomerAddress customerAddress : customerAddresses) {
listModel.addElement(customerAddress);
}
jListCustomerAddresses = new JList<>(listModel);
jListCustomerAddresses.setCellRenderer(new PanelIndividualCustomerAddress());
jListCustomerAddresses.setVisibleRowCount(2);
panelContendoOsEnderecos.add(jListCustomerAddresses);
pack();
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Ver Cliente");
}
}
LoadCustomerDataWorker.java
package testdialog;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingWorker;
import testdialog.JDViewCustomer;
import testdialog.CustomerAddress;
public class LoadCustomerDataWorker extends SwingWorker<Void, Void> {
private final JDViewCustomer dialog;
private List<CustomerAddress> customerAddresses = null;
public LoadCustomerDataWorker(JDViewCustomer dialog) {
this.dialog = dialog;
}
#Override
protected Void doInBackground() throws Exception {
customerAddresses = new ArrayList<>();
customerAddresses.add(new CustomerAddress("1. Casa"));
customerAddresses.add(new CustomerAddress("2. Trabalho"));
customerAddresses.add(new CustomerAddress("3. Casa"));
customerAddresses.add(new CustomerAddress("4. Trabalho"));
return null;
}
#Override
protected void done() {
if (customerAddresses != null && customerAddresses.size() > 0) {
dialog.addCustomerAddresses(customerAddresses);
}
}
}
PanelIndividualCustomerAddress.java
package testdialog;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import testdialog.CustomerAddress;
public class PanelIndividualCustomerAddress implements ListCellRenderer<CustomerAddress> {
#Override
public Component getListCellRendererComponent(JList<? extends CustomerAddress> list, CustomerAddress value, int index, boolean isSelected,
boolean cellHasFocus) {
JPanel panelEnderecoIndividual = new JPanel();
panelEnderecoIndividual.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(3, 3, 3, 3)));
panelEnderecoIndividual.setBackground(Color.WHITE);
panelEnderecoIndividual.setLayout(new BoxLayout(panelEnderecoIndividual, BoxLayout.Y_AXIS));
JPanel panelTituloEndereco = new JPanel();
panelTituloEndereco.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
FlowLayout fl_panelTituloEndereco = (FlowLayout) panelTituloEndereco.getLayout();
fl_panelTituloEndereco.setAlignment(FlowLayout.LEFT);
panelTituloEndereco.setBackground(new Color(220, 220, 220));
panelEnderecoIndividual.add(panelTituloEndereco);
JLabel lblCasa = new JLabel(value.getTitle()); // "Casa"
panelTituloEndereco.add(lblCasa);
JPanel panelDadosDoEndereco = new JPanel();
panelDadosDoEndereco.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelDadosDoEndereco.setBackground(Color.WHITE);
panelEnderecoIndividual.add(panelDadosDoEndereco);
GridBagLayout gbl_panelDadosDoEndereco = new GridBagLayout();
gbl_panelDadosDoEndereco.columnWidths = new int[]{83, 184, 68, 102, 65, 134, 0};
gbl_panelDadosDoEndereco.rowHeights = new int[]{0, 0, 20, 0};
gbl_panelDadosDoEndereco.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelDadosDoEndereco.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
panelDadosDoEndereco.setLayout(gbl_panelDadosDoEndereco);
JLabel lblEndereco = new JLabel("Endereço:");
lblEndereco.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblEndereo = new GridBagConstraints();
gbc_lblEndereo.anchor = GridBagConstraints.WEST;
gbc_lblEndereo.insets = new Insets(0, 0, 5, 5);
gbc_lblEndereo.gridx = 0;
gbc_lblEndereo.gridy = 0;
panelDadosDoEndereco.add(lblEndereco, gbc_lblEndereo);
JLabel lblNomeDaRua = new JLabel("Nome da rua");
GridBagConstraints gbc_lblNomeDaRua = new GridBagConstraints();
gbc_lblNomeDaRua.anchor = GridBagConstraints.WEST;
gbc_lblNomeDaRua.gridwidth = 3;
gbc_lblNomeDaRua.insets = new Insets(0, 0, 5, 5);
gbc_lblNomeDaRua.gridx = 1;
gbc_lblNomeDaRua.gridy = 0;
panelDadosDoEndereco.add(lblNomeDaRua, gbc_lblNomeDaRua);
JLabel lblNumero = new JLabel("Número:");
lblNumero.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblNumero = new GridBagConstraints();
gbc_lblNumero.anchor = GridBagConstraints.WEST;
gbc_lblNumero.insets = new Insets(0, 0, 5, 5);
gbc_lblNumero.gridx = 4;
gbc_lblNumero.gridy = 0;
panelDadosDoEndereco.add(lblNumero, gbc_lblNumero);
JLabel lblValorDoNumero = new JLabel("Valor do número");
GridBagConstraints gbc_lblValorDoNumero = new GridBagConstraints();
gbc_lblValorDoNumero.anchor = GridBagConstraints.WEST;
gbc_lblValorDoNumero.insets = new Insets(0, 0, 5, 0);
gbc_lblValorDoNumero.gridx = 5;
gbc_lblValorDoNumero.gridy = 0;
panelDadosDoEndereco.add(lblValorDoNumero, gbc_lblValorDoNumero);
JLabel lblComplemento = new JLabel("Complemento:");
lblComplemento.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblComplemento = new GridBagConstraints();
gbc_lblComplemento.anchor = GridBagConstraints.WEST;
gbc_lblComplemento.insets = new Insets(0, 0, 5, 5);
gbc_lblComplemento.gridx = 0;
gbc_lblComplemento.gridy = 1;
panelDadosDoEndereco.add(lblComplemento, gbc_lblComplemento);
JLabel lblTextoDoComplemento = new JLabel("Texto do complemento");
GridBagConstraints gbc_lblTextoDoComplemento = new GridBagConstraints();
gbc_lblTextoDoComplemento.anchor = GridBagConstraints.WEST;
gbc_lblTextoDoComplemento.insets = new Insets(0, 0, 5, 5);
gbc_lblTextoDoComplemento.gridx = 1;
gbc_lblTextoDoComplemento.gridy = 1;
panelDadosDoEndereco.add(lblTextoDoComplemento, gbc_lblTextoDoComplemento);
JLabel lblBairro = new JLabel("Bairro:");
lblBairro.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblBairro = new GridBagConstraints();
gbc_lblBairro.anchor = GridBagConstraints.WEST;
gbc_lblBairro.insets = new Insets(0, 0, 5, 5);
gbc_lblBairro.gridx = 2;
gbc_lblBairro.gridy = 1;
panelDadosDoEndereco.add(lblBairro, gbc_lblBairro);
JLabel lblNomeDoBairro = new JLabel("Nome do bairro");
GridBagConstraints gbc_lblNomeDoBairro = new GridBagConstraints();
gbc_lblNomeDoBairro.anchor = GridBagConstraints.WEST;
gbc_lblNomeDoBairro.insets = new Insets(0, 0, 5, 5);
gbc_lblNomeDoBairro.gridx = 3;
gbc_lblNomeDoBairro.gridy = 1;
panelDadosDoEndereco.add(lblNomeDoBairro, gbc_lblNomeDoBairro);
JLabel lblCidade = new JLabel("Cidade:");
lblCidade.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblCidade = new GridBagConstraints();
gbc_lblCidade.anchor = GridBagConstraints.WEST;
gbc_lblCidade.insets = new Insets(0, 0, 5, 5);
gbc_lblCidade.gridx = 4;
gbc_lblCidade.gridy = 1;
panelDadosDoEndereco.add(lblCidade, gbc_lblCidade);
JLabel lblNomeDaCidade = new JLabel("Nome da cidade");
GridBagConstraints gbc_lblNomeDaCidade = new GridBagConstraints();
gbc_lblNomeDaCidade.anchor = GridBagConstraints.WEST;
gbc_lblNomeDaCidade.insets = new Insets(0, 0, 5, 0);
gbc_lblNomeDaCidade.gridx = 5;
gbc_lblNomeDaCidade.gridy = 1;
panelDadosDoEndereco.add(lblNomeDaCidade, gbc_lblNomeDaCidade);
JLabel lblCep = new JLabel("CEP:");
lblCep.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblCep = new GridBagConstraints();
gbc_lblCep.anchor = GridBagConstraints.WEST;
gbc_lblCep.insets = new Insets(0, 0, 0, 5);
gbc_lblCep.gridx = 0;
gbc_lblCep.gridy = 2;
panelDadosDoEndereco.add(lblCep, gbc_lblCep);
JLabel lblNumeroDoCep = new JLabel("Número do CEP");
GridBagConstraints gbc_lblNumeroDoCep = new GridBagConstraints();
gbc_lblNumeroDoCep.anchor = GridBagConstraints.WEST;
gbc_lblNumeroDoCep.insets = new Insets(0, 0, 0, 5);
gbc_lblNumeroDoCep.gridx = 1;
gbc_lblNumeroDoCep.gridy = 2;
panelDadosDoEndereco.add(lblNumeroDoCep, gbc_lblNumeroDoCep);
JLabel lblPontoRef = new JLabel("Ponto ref.:");
lblPontoRef.setFont(new Font("Tahoma", Font.BOLD, 11));
GridBagConstraints gbc_lblPontoRef = new GridBagConstraints();
gbc_lblPontoRef.anchor = GridBagConstraints.WEST;
gbc_lblPontoRef.insets = new Insets(0, 0, 0, 5);
gbc_lblPontoRef.gridx = 2;
gbc_lblPontoRef.gridy = 2;
panelDadosDoEndereco.add(lblPontoRef, gbc_lblPontoRef);
JLabel lblPertoDeTalLugar = new JLabel("Perto de tal lugar");
GridBagConstraints gbc_lblPertoDeTalLugar = new GridBagConstraints();
gbc_lblPertoDeTalLugar.anchor = GridBagConstraints.WEST;
gbc_lblPertoDeTalLugar.gridwidth = 3;
gbc_lblPertoDeTalLugar.gridx = 3;
gbc_lblPertoDeTalLugar.gridy = 2;
panelDadosDoEndereco.add(lblPertoDeTalLugar, gbc_lblPertoDeTalLugar);
return panelEnderecoIndividual;
}
}
setVisibleRowCount() only works if the JList is the view of a JScrollPane (that is, the main child of the JScrollPane). In your program, the JScrollPane’s view is a JPanel, not a JList.
I've a problem with a JPanel.
It's a CardLayout and two sub-panel that change.
I need to do a button which switch from subpanel 1 to 2 and display selected Product.
ISSUE:
When I select a product card, JPanel changes but it's blank.
If I step over the window with the mouse , the buttons appear, but not the JLabels.
And If I resize the windows, it's empty again.
What is the problem?
EDIT:
Here the code that return same error.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private static final long serialVersionUID = 1L;
// private String title;
// private Dimension d;
public MainFrame(String title, Dimension d) {
// LoginPanel template = new LoginPanel(this);
// RegisterPanel template = new RegisterPanel(this);
CustomerPanel template = new CustomerPanel(this);
this.setTitle(title);
this.setSize(d);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.getContentPane().add(template);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new MainFrame("Fubars", new Dimension(800, 650));
});
}
}
#SuppressWarnings("serial")
class CustomerPanel extends JPanel {
MainFrame mf;
JPanel one, two;
JPanel panel;
public CustomerPanel(MainFrame mf) {
this.mf = mf;
mf.getContentPane().setLayout(new CardLayout(0, 0));
JPanel container = new JPanel();
mf.getContentPane().add(container, "name_36743208542992");
container.setLayout(new BorderLayout(0, 0));
JPanel back = new JPanel();
container.add(back, BorderLayout.NORTH);
back.setLayout(new FlowLayout(FlowLayout.LEFT));
JButton btnControl = new JButton("<");
back.add(btnControl);
panel = new JPanel();
container.add(panel, BorderLayout.CENTER);
CardLayout cl = new CardLayout(0, 0);
panel.setLayout(cl);
one = new OnePanel(this.mf);
two = new JPanel();
panel.add(one, "1");
panel.add(two, "2");
btnControl.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
two = new LoginPanel(mf);
cl.next(panel);
}
});
}
}
#SuppressWarnings("serial")
class LoginPanel extends JPanel {
// private MainFrame mf;
private JTextField textField;
private JPasswordField passwordField;
public LoginPanel(MainFrame mf) {
// this.mf = mf;
mf.getContentPane().setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
mf.getContentPane().add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 100, 55, 72, 171, 0 };
gbl_panel.rowHeights = new int[] { 69, 22, 22, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
JLabel lblNewLabel = new JLabel("Email");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.fill = GridBagConstraints.HORIZONTAL;
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 1;
panel.add(lblNewLabel, gbc_lblNewLabel);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.anchor = GridBagConstraints.NORTH;
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.gridx = 3;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(15);
JLabel lblNewLabel_1 = new JLabel("Password");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.anchor = GridBagConstraints.WEST;
gbc_lblNewLabel_1.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_1.gridx = 1;
gbc_lblNewLabel_1.gridy = 2;
panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
passwordField = new JPasswordField();
passwordField.setColumns(15);
GridBagConstraints gbc_passwordField = new GridBagConstraints();
gbc_passwordField.anchor = GridBagConstraints.NORTH;
gbc_passwordField.gridx = 3;
gbc_passwordField.gridy = 2;
panel.add(passwordField, gbc_passwordField);
JPanel panel_1 = new JPanel();
mf.getContentPane().add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 30));
JButton btnNewButton = new JButton("LOGIN");
panel_1.add(btnNewButton);
btnNewButton.setActionCommand("login");
JButton btnRegistration = new JButton("REGISTER");
panel_1.add(btnRegistration);
btnRegistration.setActionCommand("registration");
}
}
#SuppressWarnings("serial")
class OnePanel extends JPanel {
// private MainFrame mf;
public OnePanel(MainFrame mf) {
// this.mf = mf;
mf.getContentPane().setLayout(new CardLayout(0, 0));
JPanel container = new JPanel();
mf.getContentPane().add(container, "name_36743208542992");
container.setLayout(new BorderLayout(0, 0));
JPanel image = new JPanel();
container.add(image, BorderLayout.CENTER);
JButton btnImageBack = new JButton("<");
image.add(btnImageBack);
JLabel imageContainer = new JLabel("Images");
image.add(imageContainer);
imageContainer.setBounds(new Rectangle(100, 100, 100, 100));
imageContainer.setHorizontalTextPosition(SwingConstants.CENTER);
imageContainer.setHorizontalAlignment(SwingConstants.CENTER);
imageContainer.setAlignmentX(Component.CENTER_ALIGNMENT);
imageContainer.setIconTextGap(3);
imageContainer.setIcon(null);
JButton btnImageForward = new JButton(">");
image.add(btnImageForward);
btnImageForward.setAlignmentY(Component.BOTTOM_ALIGNMENT);
btnImageForward.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel info = new JPanel();
container.add(info, BorderLayout.EAST);
GridBagLayout gbl_info = new GridBagLayout();
gbl_info.columnWidths = new int[] { 0, 0, 63, 0, 0, 0 };
gbl_info.rowHeights = new int[] { 0, 0, 25, 0, 0, 0, 0 };
gbl_info.columnWeights = new double[] { 1.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE };
gbl_info.rowWeights = new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE };
info.setLayout(gbl_info);
JLabel lblTitle = new JLabel("Title");
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.anchor = GridBagConstraints.NORTHWEST;
gbc_lblTitle.insets = new Insets(0, 0, 5, 5);
gbc_lblTitle.gridx = 2;
gbc_lblTitle.gridy = 1;
info.add(lblTitle, gbc_lblTitle);
JLabel lblDescription = new JLabel("Description");
GridBagConstraints gbc_lblDescription = new GridBagConstraints();
gbc_lblDescription.anchor = GridBagConstraints.WEST;
gbc_lblDescription.insets = new Insets(0, 0, 5, 5);
gbc_lblDescription.gridx = 2;
gbc_lblDescription.gridy = 2;
info.add(lblDescription, gbc_lblDescription);
JLabel lblPrice = new JLabel("Price");
GridBagConstraints gbc_lblPrice = new GridBagConstraints();
gbc_lblPrice.anchor = GridBagConstraints.WEST;
gbc_lblPrice.insets = new Insets(0, 0, 5, 5);
gbc_lblPrice.gridx = 2;
gbc_lblPrice.gridy = 3;
info.add(lblPrice, gbc_lblPrice);
lblPrice.setToolTipText("Price");
JButton btnAddCart = new JButton("Add to Cart");
GridBagConstraints gbc_btnAddCart = new GridBagConstraints();
gbc_btnAddCart.insets = new Insets(0, 0, 5, 5);
gbc_btnAddCart.anchor = GridBagConstraints.WEST;
gbc_btnAddCart.gridx = 2;
gbc_btnAddCart.gridy = 4;
info.add(btnAddCart, gbc_btnAddCart);
}
}
The class where I declared and set the variable.
The variable userQuestion is being set each time the user activates a button. The purpose is so that it can be used in the next class to reask that question. However, it seems like the userQuestion variable is not being set. Sorry for the messy code, it was made using Window Builder in Eclipse.
https://pastebin.com/azP6SbRa
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
public class createprojecte extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnWhatIsYour;
private JButton btnWhereDidYour;
private JButton btnWhatWasThe;
private JButton btnWhoIsYour;
private JButton btnWhatIsYour_1;
private JButton btnWhatIsYour_2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
createprojecte frame = new createprojecte();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
})
;
}
String userQuestion;
public createprojecte() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{424, 0};
gbl_contentPane.rowHeights = new int[]{20, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
textField = new JTextField();
textField.setText("Choose what security option you want:");
textField.setColumns(10);
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.anchor = GridBagConstraints.NORTH;
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 0;
gbc_textField.gridy = 0;
contentPane.add(textField, gbc_textField);
btnWhatIsYour = new JButton("What is your mother's maiden name?");
btnWhatIsYour.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input frame = new input();
frame.setVisible(true);
String userQuestion = "What is your mother's maiden name?";
frame.SetUserQuestion(userQuestion);
}
});
GridBagConstraints gbc_btnWhatIsYour = new GridBagConstraints();
gbc_btnWhatIsYour.insets = new Insets(0, 0, 5, 0);
gbc_btnWhatIsYour.gridx = 0;
gbc_btnWhatIsYour.gridy = 2;
contentPane.add(btnWhatIsYour, gbc_btnWhatIsYour);
btnWhereDidYour = new JButton("Where did your parents meet?");
btnWhereDidYour.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input frame = new input();
frame.setVisible(true);
String userQuestion = "Where did your parents meet?";
}
});
GridBagConstraints gbc_btnWhereDidYour = new GridBagConstraints();
gbc_btnWhereDidYour.insets = new Insets(0, 0, 5, 0);
gbc_btnWhereDidYour.gridx = 0;
gbc_btnWhereDidYour.gridy = 3;
contentPane.add(btnWhereDidYour, gbc_btnWhereDidYour);
btnWhatWasThe = new JButton("What was the first street you lived on?");
btnWhatWasThe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input frame = new input();
frame.setVisible(true);
String userQuestion = "What was the first street you lived on?";
}
});
GridBagConstraints gbc_btnWhatWasThe = new GridBagConstraints();
gbc_btnWhatWasThe.insets = new Insets(0, 0, 5, 0);
gbc_btnWhatWasThe.gridx = 0;
gbc_btnWhatWasThe.gridy = 4;
contentPane.add(btnWhatWasThe, gbc_btnWhatWasThe);
btnWhoIsYour = new JButton("Who is your favorite music group?");
btnWhoIsYour.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input frame = new input();
frame.setVisible(true);
String userQuestion = "Who is your favorite music group?";
}
});
GridBagConstraints gbc_btnWhoIsYour = new GridBagConstraints();
gbc_btnWhoIsYour.insets = new Insets(0, 0, 5, 0);
gbc_btnWhoIsYour.gridx = 0;
gbc_btnWhoIsYour.gridy = 5;
contentPane.add(btnWhoIsYour, gbc_btnWhoIsYour);
btnWhatIsYour_1 = new JButton("What is your favorite book?");
btnWhatIsYour_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input frame = new input();
frame.setVisible(true);
String userQuestion = "What is your favorite book?";
}
});
GridBagConstraints gbc_btnWhatIsYour_1 = new GridBagConstraints();
gbc_btnWhatIsYour_1.insets = new Insets(0, 0, 5, 0);
gbc_btnWhatIsYour_1.gridx = 0;
gbc_btnWhatIsYour_1.gridy = 6;
contentPane.add(btnWhatIsYour_1, gbc_btnWhatIsYour_1);
btnWhatIsYour_2 = new JButton("What is your favorite sports team?");
btnWhatIsYour_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input frame = new input();
frame.setVisible(true);
String userQuestion = "What is your favorite sports team?";
}
});
GridBagConstraints gbc_btnWhatIsYour_2 = new GridBagConstraints();
gbc_btnWhatIsYour_2.insets = new Insets(0, 0, 5, 0);
gbc_btnWhatIsYour_2.gridx = 0;
gbc_btnWhatIsYour_2.gridy = 7;
contentPane.add(btnWhatIsYour_2, gbc_btnWhatIsYour_2);
}
}
The class where I am trying to access the variable.
https://pastebin.com/vb6MWeba
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import javax.swing.JPasswordField;
import java.awt.Insets;
public class input extends JFrame {
private JTextField txtWhatIsThe;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
input frame = new input();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
String userQuestion;
public void SetUserQuestion(String question)
{
this.userQuestion = question;
}
public input() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(null);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
getContentPane().setLayout(gridBagLayout);
txtWhatIsThe = new JTextField();
txtWhatIsThe.setText(userQuestion );
GridBagConstraints gbc_txtWhatIsThe = new GridBagConstraints();
gbc_txtWhatIsThe.insets = new Insets(0, 0, 5, 0);
gbc_txtWhatIsThe.fill = GridBagConstraints.HORIZONTAL;
gbc_txtWhatIsThe.gridx = 0;
gbc_txtWhatIsThe.gridy = 0;
getContentPane().add(txtWhatIsThe, gbc_txtWhatIsThe);
txtWhatIsThe.setColumns(10);
}
}
You are not really setting your questions into the frame in some of your listeners:
btnWhatIsYour_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input frame = new input();
frame.setVisible(true);
String userQuestion = "What is your favorite book?";
// Missing setter
}
});
I've read the documentation for GridBagLayout and I can't make sense of it. I basically want to accomplish something like this:
I made some example code to help me figure this out. How can I modify this code to accomplish this?
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JLabel label = new JLabel("label");
JTextField field = new JTextField();
JLabel label2 = new JLabel("label2");
JTextField field2 = new JTextField();
JPanel jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
//gbc.weightx = ??
jp.add(label, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
//gbc.weightx = ??
jp.add(field, gbc);
JPanel jp2 = new JPanel();
jp2.setLayout(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.fill = GridBagConstraints.BOTH;
gbc2.gridx = 0;
gbc2.gridy = 0;
gbc2.gridwidth = 1;
//gbc2.weightx = ??
jp2.add(label2, gbc2);
gbc2.gridx = 1;
gbc2.gridwidth = 2;
//gbc2.weightx = ??
jp2.add(field2, gbc2);
JPanel jpContainer = new JPanel();
jpContainer.setLayout(new BoxLayout(jpContainer, BoxLayout.Y_AXIS));
jpContainer.add(jp);
jpContainer.add(jp2);
JFrame f = new JFrame();
f.setSize(300, 100);
f.setContentPane(jpContainer);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
EDIT: Changed JTextArea to JTextField
Using GridBagLayout columnWidths you can manually adjust the widths and then set the GridBagConstraints fill to GridBagConstraints.HORIZONTAL :
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import javax.swing.JTextField;
import java.awt.Insets;
public class Example extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Example frame = new Example();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Example() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] {100, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblNewLabel = new JLabel("jlabel");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.anchor = GridBagConstraints.WEST;
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
contentPane.add(lblNewLabel, gbc_lblNewLabel);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
contentPane.add(textField, gbc_textField);
textField.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("jlabel2");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.anchor = GridBagConstraints.WEST;
gbc_lblNewLabel_1.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 1;
contentPane.add(lblNewLabel_1, gbc_lblNewLabel_1);
textField_1 = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 1;
gbc_textField_1.gridy = 1;
contentPane.add(textField_1, gbc_textField_1);
textField_1.setColumns(10);
}
}
Of course, if you want to maintain the 1/3 Label and 2/3 JTextField, you might consider using a MigLayout as such:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class MigLayoutExample extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MigLayoutExample frame = new MigLayoutExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MigLayoutExample() {
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(new MigLayout("", "[grow 33][grow 66]", "[][]"));
JLabel lblNewLabel = new JLabel("New label");
contentPane.add(lblNewLabel, "cell 0 0");
textField = new JTextField();
contentPane.add(textField, "cell 1 0,growx");
textField.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("New label");
contentPane.add(lblNewLabel_1, "cell 0 1");
textField_1 = new JTextField();
contentPane.add(textField_1, "cell 1 1,growx");
textField_1.setColumns(10);
}
}
You only have two components on each row so you can only have two columns.
If you want the JTextArea to occupy more space then define the JTextArea like:
JTextArea textArea = new JTextArea(3, 30);
to control the size of the text area by specifying the row/columns of the text area.
I'm not sure why you are using a JTextArea. It seems like a JTextField would be more appropriate. You can also specify the columns when you create a JTextField. Check out the JTextField API.