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?
Related
I have made a parentPanel that has a CardLayout on it, and under this I've made 4 more JPanel containers.
On the left side I have 4 buttons that when I press "Forside" (button) I want to switch to the panel on the card layout (Forside) and so on...
I've tried different youtube tutorials and tried to look on here without any success.
Everything I have tried has ended up with a NullPointerException
public class Main extends JFrame {
private JPanel contentPane;
int xx, xy;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setUndecorated(true); // Hides the jframe top bar
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 735, 506);
contentPane = new JPanel();
contentPane.setBackground(new Color(102, 102, 102));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panelLeft = new JPanel();
panelLeft.setBackground(new Color(51, 51, 51));
panelLeft.setForeground(Color.DARK_GRAY);
panelLeft.setBounds(0, 54, 150, 459);
contentPane.add(panelLeft);
panelLeft.setLayout(null);
JButton btnForside = new JButton("Forside");
btnForside.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnForside.setForeground(Color.WHITE);
btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
btnForside.setContentAreaFilled(false);
btnForside.setBorderPainted(false);
btnForside.setBorder(null);
btnForside.setBounds(16, 60, 112, 30);
panelLeft.add(btnForside);
JButton btnDagbog = new JButton("Dagbog");
btnDagbog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnDagbog.setContentAreaFilled(false);
btnDagbog.setBorderPainted(false);
btnDagbog.setBorder(null);
btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnDagbog.setForeground(Color.WHITE);
btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
btnDagbog.setBounds(16, 116, 112, 30);
panelLeft.add(btnDagbog);
JButton btnAftaler = new JButton("Aftaler");
btnAftaler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAftaler.setContentAreaFilled(false);
btnAftaler.setBorderPainted(false);
btnAftaler.setBorder(null);
btnAftaler.setForeground(Color.WHITE);
btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
btnAftaler.setBounds(16, 173, 112, 30);
panelLeft.add(btnAftaler);
JButton btnKontakt = new JButton("Kontakt");
btnKontakt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnKontakt.setContentAreaFilled(false);
btnKontakt.setBorder(null);
btnKontakt.setBorderPainted(false);
btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnKontakt.setForeground(Color.WHITE);
btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
btnKontakt.setBounds(16, 231, 112, 30);
panelLeft.add(btnKontakt);
JPanel panelTop = new JPanel();
panelTop.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
Main.this.setLocation(x - xx, y - xy); // makes uggerhøj picture dragable
}
});
panelTop.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xx = e.getX(); // makes uggerhøj picture dragable
xy = e.getY(); // makes uggerhøj picture dragable
}
});
panelTop.setBackground(new Color(51, 51, 51));
panelTop.setBounds(0, 0, 737, 60);
contentPane.add(panelTop);
panelTop.setLayout(null);
JButton btnX = new JButton("X");
btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnX.setRolloverIcon(null);
btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
btnX.setFocusTraversalKeysEnabled(false);
btnX.setFocusPainted(false);
btnX.setBorderPainted(false);
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnX.setContentAreaFilled(false);
btnX.setForeground(SystemColor.activeCaption);
btnX.setBorder(null);
btnX.setBounds(615, 13, 97, 25);
panelTop.add(btnX);
JPanel parentPanel = new JPanel();
parentPanel.setBackground(Color.GRAY);
parentPanel.setBounds(148, 54, 569, 405);
contentPane.add(parentPanel);
parentPanel.setLayout(new CardLayout(0, 0));
JPanel Forside = new JPanel();
parentPanel.add(Forside, "name_1472174211097300");
Forside.setFocusable(false);
JButton btnTest = new JButton("test");
Forside.add(btnTest);
JPanel Dagbog = new JPanel();
parentPanel.add(Dagbog, "name_1472176236196000");
JLabel lblTest = new JLabel("dagbog");
Dagbog.add(lblTest);
JPanel Aftaler = new JPanel();
parentPanel.add(Aftaler, "name_1472177885026100");
JPanel Kontakt = new JPanel();
parentPanel.add(Kontakt, "name_1472179607862700");
}
}
I'd just want it so the right buttons leads to the right cards.
first of all please next time take #AndrewThompson advise about making a MCVE of your code and #camickr advise about the test and debug in little steps before going to the real code (this is the expert programming 101).
the CardLayout object switches between the content of the container via the method
CardLayout.show(Container parent, String name);
keep in mind when making navigation in your swing code DO-NOT make your Components fields in a method instead make it local variables (at least in your case the parentPanel and the CardLayout)
so in order to make your parentPanel switch between your 4 panels (sorry am not familiar with your language) i did a fairly refactored version of your code .
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
private JPanel contentPane;
int xx, xy;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setUndecorated(true); // Hides the jframe top bar
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 735, 506);
contentPane = new JPanel();
contentPane.setBackground(new Color(102, 102, 102));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Forside = new JPanel();
JPanel Dagbog = new JPanel();
JPanel Aftaler = new JPanel();
JPanel Kontakt = new JPanel();
JPanel panelLeft = new JPanel();
panelLeft.setBackground(new Color(51, 51, 51));
panelLeft.setForeground(Color.DARK_GRAY);
panelLeft.setBounds(0, 54, 150, 459);
contentPane.add(panelLeft);
panelLeft.setLayout(null);
JButton btnForside = new JButton("Forside");
btnForside.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setCardLayoutView("name_1472174211097300");
}
});
btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnForside.setForeground(Color.WHITE);
btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
btnForside.setContentAreaFilled(false);
btnForside.setBorderPainted(false);
btnForside.setBorder(null);
btnForside.setBounds(16, 60, 112, 30);
panelLeft.add(btnForside);
JButton btnDagbog = new JButton("Dagbog");
btnDagbog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472176236196000");
}
});
btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnDagbog.setContentAreaFilled(false);
btnDagbog.setBorderPainted(false);
btnDagbog.setBorder(null);
btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnDagbog.setForeground(Color.WHITE);
btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
btnDagbog.setBounds(16, 116, 112, 30);
panelLeft.add(btnDagbog);
JButton btnAftaler = new JButton("Aftaler");
btnAftaler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472177885026100");
}
});
btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAftaler.setContentAreaFilled(false);
btnAftaler.setBorderPainted(false);
btnAftaler.setBorder(null);
btnAftaler.setForeground(Color.WHITE);
btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
btnAftaler.setBounds(16, 173, 112, 30);
panelLeft.add(btnAftaler);
JButton btnKontakt = new JButton("Kontakt");
btnKontakt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472179607862700");
}
});
btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnKontakt.setContentAreaFilled(false);
btnKontakt.setBorder(null);
btnKontakt.setBorderPainted(false);
btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnKontakt.setForeground(Color.WHITE);
btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
btnKontakt.setBounds(16, 231, 112, 30);
panelLeft.add(btnKontakt);
JPanel panelTop = new JPanel();
panelTop.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
Main.this.setLocation(x - xx, y - xy); // makes uggerhøj picture dragable
}
});
panelTop.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xx = e.getX(); // makes uggerhøj picture dragable
xy = e.getY(); // makes uggerhøj picture dragable
}
});
panelTop.setBackground(new Color(51, 51, 51));
panelTop.setBounds(0, 0, 737, 60);
contentPane.add(panelTop);
panelTop.setLayout(null);
JButton btnX = new JButton("X");
btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnX.setRolloverIcon(null);
btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
btnX.setFocusTraversalKeysEnabled(false);
btnX.setFocusPainted(false);
btnX.setBorderPainted(false);
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnX.setContentAreaFilled(false);
btnX.setForeground(SystemColor.activeCaption);
btnX.setBorder(null);
btnX.setBounds(615, 13, 97, 25);
panelTop.add(btnX);
parentPanel = new JPanel();
parentPanel.setBackground(Color.GRAY);
parentPanel.setBounds(148, 54, 569, 405);
contentPane.add(parentPanel);
cardLayoutObject = new CardLayout(0, 0);
parentPanel.setLayout(cardLayoutObject);
parentPanel.add(Forside, "name_1472174211097300");
Forside.setFocusable(false);
JButton btnTest = new JButton("test");
Forside.add(btnTest);
parentPanel.add(Dagbog, "name_1472176236196000");
JLabel lblTest = new JLabel("dagbog");
Dagbog.add(lblTest);
parentPanel.add(Aftaler, "name_1472177885026100");
parentPanel.add(Kontakt, "name_1472179607862700");
}
private CardLayout cardLayoutObject;
private JPanel parentPanel;
private void setCardLayoutView(String viewName) {
cardLayoutObject.show(parentPanel, viewName);
}
}
and happy coding ^-^.
I want to add a dynamic checkbox after selecting an item in combo box.
I am working on eclipse and design my frame on window builder.
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
c.setVisible(true);
coursePanel.add(c);
frame.repaint();
frame.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
edit: thats my full code.
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
final JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(75, 171, 221, 39);
frame.getContentPane().add(dateChooser);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton btnSend = new JButton("\u05E9\u05DC\u05D7");
btnSend.setBounds(258, 334, 61, 58);
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// date
Date date = new Date(dateChooser.getDate().getTime());
}
});
frame.getContentPane().add(btnSend);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = c.getParent() == coursePanel;
if (selectedIndex == 1 && !isInPanel) {
coursePanel.add(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
} else if (isInPanel && selectedIndex != 1) {
coursePanel.remove(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
}
coursePanel.repaint();
coursePanel.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
List<String> lst = SqlQuery.getTypes();
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Hope you understand what I wrote. I want to show a list of coursesName after click on the comboBox.
Why the frame does'nt show the checkbox?
Thank you.
First and foremost. The comboBox.setBounds() is a very bad practice. Take some time and see Layout Managers. Also add 'swing' tag in your post since you are referring to Swing library.
The frame doesn't show the component because you repaint the wrong one. You add the checkbox in coursePanel, which means you have to repaint() & revalidate() coursePanel. So coursePanel.repaint() instead of frame.repaint() will help you.
Also checkBox.setVisible(true)is not required, since checkBox is visible by default.
Finally i have added the way of how i would do it.
package test;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame frame;
private JCheckBox checkBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
frame = new JFrame();
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createPanel());
frame.pack();
}
private JPanel createPanel() {
JPanel p = new JPanel(new FlowLayout());
checkBox = new JCheckBox("I am a checkbox"); //Create the checkbox
JComboBox<String> combo = new JComboBox<>();
combo.addItem("Hello");
combo.addItem("Stack");
combo.addItem("OverFlow");
combo.addActionListener(e -> {
//Its better to handle indices when there is not dynmic data to your combobox
int selectedIndex = combo.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == p;
if (selectedIndex == 1 && !isInPanel) {
p.add(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
} else if (isInPanel && selectedIndex != 1) {
p.remove(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
}
});
p.add(combo);
return p;
}
}
The answer to your problem (make the checkbox visible) after comments:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
private JCheckBox checkBox;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
List<String> lst = new ArrayList<>();
lst.add("Hello");
lst.add("Stack");
lst.add("Over");
lst.add("Flow");
//Prepare the checkBox
checkBox = new JCheckBox("nothing");
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < lst.size(); i++) {
checkBox.setText(typeName);
//set the same bounds as comboBox but reduce its X by 80.
//Compare checkBoxbounds and combobox bounds
//Remind: setBounds is baaaaad practice.
checkBox.setBounds(128, 221, 91, 20);
//if you want to add it in coursePanel, change all frame.getContentPane() to coursePanel
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == frame.getContentPane();
if (selectedIndex == 1 && !isInPanel) {
frame.getContentPane().add(checkBox);
} else if (isInPanel && selectedIndex != 1) {
frame.getContentPane().remove(checkBox);
}
frame.getContentPane().repaint();
frame.getContentPane().validate();
System.out.println(checkBox.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Another option is to create the checkbox as a field outside of the actionlistener (like i did) and set its bounds with window builder and use setVisible(false). Then on your listener, setVisible(true)
Like the title said, the hearder name is just not showing up. i tried many options like using a JScrollPane. and fallowed many guide on this forum but no help. I really wanted to get resolve problem by myself but i have tried everything and out of option.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.ScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
public class Adminpage extends JPanel {
private JFrame frame;
static String ID[]={"name","Username","Password"};
static DefaultTableModel model;
private JTextField NametextField;
private JTextField UsertextField;
private JTextField PasstextField;
private JTable table;
private JScrollPane scroll;
/**
* Create the panel.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 497, 545);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblAdminstratorPortal = new JLabel("Adminstrator Portal");
lblAdminstratorPortal.setFont(new Font("Tahoma", Font.BOLD, 20));
lblAdminstratorPortal.setBounds(109, 26, 218, 25);
frame.getContentPane().add(lblAdminstratorPortal);
JButton btnNewButton = new JButton("Add Librarian");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//model= (DefaultTableModel)table.getModel();
//model.addColumn("name");
//model.addColumn("Username");
//model.addColumn("Password");
model.addRow(new Object[]{NametextField.getText(),UsertextField.getText(),PasstextField.getText()});
}
});
btnNewButton.setBounds(10, 62, 108, 35);
frame.getContentPane().add(btnNewButton);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDelete.setBounds(130, 62, 108, 35);
frame.getContentPane().add(btnDelete);
JButton btnViewLibrarian = new JButton("View Librarian");
btnViewLibrarian.setBounds(245, 62, 108, 35);
frame.getContentPane().add(btnViewLibrarian);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
}
});
btnLogout.setBounds(363, 62, 108, 35);
frame.getContentPane().add(btnLogout);
//model= (DefaultTableModel)table.getModel();
JLabel lblName = new JLabel("Name");
lblName.setBounds(21, 144, 60, 14);
frame.getContentPane().add(lblName);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(21, 195, 60, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(21, 250, 60, 14);
frame.getContentPane().add(lblPassword);
NametextField = new JTextField();
NametextField.setBounds(119, 141, 119, 20);
frame.getContentPane().add(NametextField);
NametextField.setColumns(10);
UsertextField = new JTextField();
UsertextField.setColumns(10);
UsertextField.setBounds(119, 192, 119, 20);
frame.getContentPane().add(UsertextField);
PasstextField = new JTextField();
PasstextField.setColumns(10);
PasstextField.setBounds(119, 247, 119, 20);
frame.getContentPane().add(PasstextField);
table = new JTable();
table.setBounds(10, 304, 461, 189);
frame.getContentPane().add(table);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Adminpage() {
database();
setLayout(null);
initialize();
model= (DefaultTableModel)table.getModel();
model.addColumn("name");
model.addColumn("Username");
model.addColumn("Password");
}
public void database(){
try {
Class.forName("sun.jdbc.odbc.JdbsOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Games");
Statement st = con.createStatement();
String getquery = ("Select* from Games");
ResultSet rs= st.executeQuery(getquery);
while(rs.next()){
System.out.println(rs.getString(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
You're adding the JTable directly to the GUI. Instead, yes you need to embed the JTable into the viewport of a JScrollPane and then add the JScrollPane to the GUI.
For example:
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
// table.setBounds(10, 304, 461, 189);
scrollPane.setBounds(10, 304, 461, 189); // This is bad, but will leave for now
// frame.getContentPane().add(table);
frame.getContentPane().add(scrollPane);
Also, you're harming your GUI by using null layouts and absolute positioning, as this can interfere with a component's ability to show itself fully and correctly, to achieve its own preferred size. Much better is to learn and use the layout managers.
For instance, when I run your program on my platform, I see:
Note how the buttons do not show their full texts due to their not being allowed to achieve their preferred sizes.
For example, using BoxLayout with some nested JPanels, one using GridLayout(1, 0, 5, 0) for one row, variable number of columns, and a 5 point horizontal gap between components, and another nested JPanel using GridBagLayout, for placement of JTextFields and JLabels, and some "wrapper" JPanels using default FlowLayout to center components within them...
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AdminPage2 extends JPanel {
private static final long serialVersionUID = 1L;
public static final String TITLE = "Administrator Portal";
private static final Font TITLE_FONT = new Font("Tahoma", Font.BOLD, 20);
private static final String[] COL_NAMES = {"Name", "User Name", "Password"};
private int txtFieldCols = 20;
private JTextField nameField = new JTextField(txtFieldCols);
private JTextField userNameField = new JTextField(txtFieldCols);
private JPasswordField passwordField = new JPasswordField(txtFieldCols);
private DefaultTableModel tableModel = new DefaultTableModel(COL_NAMES, 0);
private JTable table = new JTable(tableModel);
private JScrollPane tableScrollPane = new JScrollPane(table);
public AdminPage2() {
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(TITLE_FONT);
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
// of course you'd add ActionListeners or Actions to your buttons
buttonPanel.add(new JButton("Add Library"));
buttonPanel.add(new JButton("Delete"));
buttonPanel.add(new JButton("View Library"));
buttonPanel.add(new JButton("Logout"));
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
JPanel wrapTfPanel = new JPanel();
wrapTfPanel.add(textFieldPanel);
Dimension scrollPanePrefSz = tableScrollPane.getPreferredSize();
int w = scrollPanePrefSz.width;
int h = scrollPanePrefSz.height / 2;
scrollPanePrefSz = new Dimension(w, h);
tableScrollPane.setPreferredSize(scrollPanePrefSz);
// put together main JPanel components
int ebGap = 4;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(Box.createVerticalStrut(5));
add(titlePanel);
add(Box.createVerticalStrut(5));
add(buttonPanel);
add(Box.createVerticalStrut(5));
add(wrapTfPanel);
add(Box.createVerticalStrut(5));
add(tableScrollPane);
}
// create constraints to use when adding component to GridBagLayout
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
int in = 10;
int leftIn = x == 0 ? 4 * in : in;
gbc.insets = new Insets(in, leftIn, in, in);
return gbc;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
AdminPage2 mainPanel = new AdminPage2();
JFrame frame = new JFrame("Administrator Page");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Which displays as:
Regarding your questions:
but new question why give the scrollpane a bound instead of the table itself
The JScrollPane holds the JTable within it, and so if you use null layouts (which you shouldn't), and you're adding this JTable-containing JScrollPane to the GUI, you must set its bounds. Much better though is to use layout managers as I've outlined above. It makes it much easier to modify the GUI later and to debug it now.
and why adding the scrollpane into the panel instead of the table.
Because that's how JScrollPanes work. They don't add scrollbars to a component but rather nest the component itself, here the JTable, within the JScrollPane's viewport. Please read the JScrollPane Tutorial (see link) to see the details on this.
A further note on the power of layout managers. Say you want to add a new JLabel / JTextField combination, one that accepts a password hint, and say the JTextField's name is passwordHint. If you were using null layouts and absolute positioning, you'd have to set the bounds of your new JLabel and JTextField, but you'd also have to change the bounds of all components below and to the right of it, and would have to re-set the size of the GUI manually. If your GUI is very complex, this can lead to bugs and a lot of frustration.
If you used the layout managers above however, all you'd need to do would be to add two lines of code to the textFieldPanel JPanel creational code as shown below with the obvious comments:
// original textFieldPanel creational code
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
// !! ****** these lines added ******
textFieldPanel.add(new JLabel("Password Hint:"), createGbc(0, 3));
textFieldPanel.add(passwordHint, createGbc(1, 3));
This results in a perfect placement of the new components without adversely affecting the old:
I have two GUI classes. When I click a row in JTable in the first user interface, the second interface should display the corresponding values in JLabels.
But the second user interface does not show the values.
Here's my first GUI class:
public class ChequeGUI extends JFrame {
public String chqNo;
public String payName;
public double chkAmount = 10;
public Date chkDate;
JTable guiTable = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"Cheque Number","Payee Name","Cheque Amount","Cheque Date"});
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
//guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
chqNo = (String) guiTable.getValueAt(row,0);
payName = (String) guiTable.getValueAt(row,1);
chkAmount = (Double) guiTable.getValueAt(row,2);
chkDate = (Date) guiTable.getValueAt(row, 3);
try {
PrintChequeGUI pcg = new PrintChequeGUI();
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
System.out.println(chqNo);
System.out.println(payName);
System.out.println(chkAmount);
System.out.println(chkDate);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
guiTable.setModel(model);
add(new JScrollPane(guiTable));
DBConnection connection = new DBConnection();
//Populate Table
ChequeDAOImpl chqdi = new ChequeDAOImpl();
chqdi.setConnection(connection);
List<Cheque> cheques = chqdi.getCheques();
for(Cheque cq : cheques){
model.addRow(new Object[]{cq.getChqNum(), cq.getName(),cq.getAmount(),cq.getDate()});
}
}
}
This is my second GUI class:
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
* #throws SQLException
*/
public PrintChequeGUI() throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(gui.chqNo);
lblAmount.setText(Double.toString(gui.chkAmount));
lblName.setText(gui.payName);
lblDate.setText(String.valueOf(gui.chkDate));
}
}
This can be solved in many ways:
1.
As I mentioned in my comment, Pass the current instance of ChequeGUI to the constructor of PrintChequeGUI and use that instance instead of creating new one in PrintChequeGUI
PrintChequeGUI pcg = new PrintChequeGUI(this);
and in PrintChequeGUI class
public PrintChequeGUI(ChequeGUI gui) throws SQLException {
(but i think its not a good approach)
2.
For Better option, Pass the selected instance of Cheque to PrintChequeGUI as constructor argument. For this you need to create a TableModel with instance of Cheque.
Sample is given below:
package com.test;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class ChequeGUI extends JFrame {
JTable guiTable = new JTable();
ChequeTableModel model;
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
Cheque c = model.getChequeByRow(row);
try {
PrintChequeGUI pcg = new PrintChequeGUI(c);
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
model = new ChequeTableModel();
guiTable.setModel(model);
add(new JScrollPane(guiTable));
model.loadData();
}
public class ChequeTableModel extends AbstractTableModel {
List<Cheque> dataModel;
String[] columns = { "Cheque Number", "Payee Name", "Cheque Amount",
"Cheque Date" };
public ChequeTableModel() {
super();
dataModel = new ArrayList<Cheque>();
}
#Override
public int getColumnCount() {
return columns.length;
}
#Override
public String getColumnName(int column) {
return columns[column];
}
#Override
public int getRowCount() {
return dataModel.size();
}
#Override
public Object getValueAt(int row, int column) {
Object value = null;
Cheque c = getChequeByRow(row);
switch (column) {
case 0:
value = c.chqNo;
break;
case 1:
value = c.payName;
break;
case 2:
value = c.chkAmount;
break;
case 3:
value = c.chkDate;
break;
default:
break;
}
return value;
}
public Cheque getChequeByRow(int row) {
if (dataModel.size() <= 0)
return null;
if (row < 0)
return null;
return dataModel.get(row);
}
public void loadData() {
/*
*
* //Uncomment this for database connection and load data from
* database; //Please note to disconnect database if not needed
*
*
* DBConnection connection = new DBConnection();
*
* // Populate Table ChequeDAOImpl chqdi = new ChequeDAOImpl();
* chqdi.setConnection(connection); List<Cheque> cheques =
* chqdi.getCheques();
*
* for (Cheque cq : cheques) { model.addRow(new Object[] {
* cq.getChqNum(), cq.getName(), cq.getAmount(), cq.getDate() }); }
*/
for (int i = 0; i < 10; i++) {
Cheque c = new Cheque();
c.chkAmount = i * 1000;
c.chqNo = String.valueOf(i);
c.chkDate = new Date(System.currentTimeMillis());
dataModel.add(c);
}
fireTableRowsInserted(0, dataModel.size());
}
}
public static void main(String[] args) throws SQLException {
ChequeGUI c = new ChequeGUI();
c.pack();
c.setVisible(true);
}
}
Second class
package com.test;
import java.awt.Color;
import java.awt.SystemColor;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
*
* #throws SQLException
*/
public PrintChequeGUI(Cheque cheque) throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
// ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(cheque.chqNo);
lblAmount.setText(Double.toString(cheque.chkAmount));
lblName.setText(cheque.payName);
lblDate.setText(String.valueOf(cheque.chkDate));
}
}
The Cheque class you already used to get details from database
I'm new to java so bear with me:
I want the size of the window/pane/panel to chance once the tab is clicked/changed.
How would I do/impletement this?
I've done it successfully on a button click/event, but how do I do a tab click/event?
Here is my code: (I'm sorry for any bad/bloated/unnessicary code in advance)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
//Class shows how to setup up a tabbed window
public class GUI implements ActionListener
{
static JFrame aWindow = new JFrame("Project");
JTabbedPane myTabs = new JTabbedPane();
JPanel loginMainPanel = new JPanel();
JPanel displayMainPanel = new JPanel();
JPanel editMainPanel = new JPanel();
JLabel loginLabel = new JLabel("Username:");
JTextField loginField = new JTextField();
JLabel loginLabel2 = new JLabel("Password:");
JPasswordField loginPass = new JPasswordField();
JButton displayButton = new JButton("Press This Button");
JButton loginButton = new JButton("Login");
JLabel editLabel = new JLabel("Write a story:");
JTextArea editArea = new JTextArea();
public GUI()
{
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize=theKit.getScreenSize();
aWindow.setBounds(wndSize.width/3, wndSize.height/3, 200, 200); //set position, then dimensions
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(1,1);
Container content = aWindow.getContentPane();
content.setLayout(grid);
createLoginPanel();
createDisplayPanel();
createEditPanel();
myTabs.addTab("Login", loginMainPanel);
myTabs.addTab("Display", displayMainPanel);
myTabs.addTab("Edit", editMainPanel);
myTabs.setSelectedIndex(0);
//myTabs.setEnabledAt(1,false);
myTabs.setEnabledAt(2, false);
content.add(myTabs);
aWindow.setVisible(true);
}
public void createLoginPanel()
{
loginMainPanel.setLayout(null);
loginLabel.setBounds(10, 15, 150, 20);
loginMainPanel.add(loginLabel);
loginField.setBounds(10, 35, 150, 20);
loginMainPanel.add(loginField);
loginLabel2.setBounds(10, 60, 150, 20);
loginMainPanel.add(loginLabel2);
loginPass.setBounds(10, 80, 150, 20);
loginMainPanel.add(loginPass);
loginButton.addActionListener(this);
loginButton.setBounds(50, 110, 80, 20);
loginMainPanel.add(loginButton);
}
public void createDisplayPanel()
{
//Toolkit theKit = aWindow.getToolkit();
//Dimension wndSize = theKit.getScreenSize();
//aWindow.setBounds(20, 20, 20, 20); //set position, then dimensions
displayMainPanel.setLayout(null);
displayButton.addActionListener(this);
displayButton.setBounds(10, 80, 150, 20);
displayMainPanel.add(displayButton);
}
public void createEditPanel()
{
editMainPanel.setLayout(null);
editLabel.setBounds(10, 15, 150, 20);
editMainPanel.add(editLabel);
editArea.setBounds(10, 65, 150, 50);
editMainPanel.add(editArea);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
//System.out.println("Working...");
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize = theKit.getScreenSize();
aWindow.setBounds(wndSize.width / 4, wndSize.height / 4, 300, 300);
}
//Would the event go here?
}
public static void main(String[] args)
{
GUI tw1 = new GUI();
}
}
Thanks very much :)
James,
but how do I do a tab click/event?
Use a ChangeListener.