How to position components in a JFrame? - java

jframe = new JFrame("Admin");
jpanel = new JPanel();
jpanel.setLayout(new FlowLayout());
jframe.add(jpanel);
userLabel = new JLabel("Username:");
jpanel.add(userLabel);
userLabel.setBounds(100, 100, 30, 30);
userTxtfield = new JTextField(15);
jpanel.add(userTxtfield);
passwordTxtfield = new JTextField(15);
jpanel.add(userTxtfield);
jpanel.add(passwordTxtfield);
passwordLabel = new JLabel("Password:");
jpanel.add(passwordLabel);
userLabel.setBounds(100, 100, 30, 30);
loginButton= new JButton("Login");
jpanel.add(loginButton);
jframe.pack();
jframe.setLocationRelativeTo(null);
jframe.setSize(350,350);
jframe.setVisible(true);
I am trying to make a neat login area for my program but I can't seem to get the two labels and text fields to line up with the button underneath. Is there a better way of doing this positioning of the components within this JFrame?

Use a JOptionPane to display a log-in dialog. One way to layout the components is to use a GridBagLayout.
The code that produces that is:
public void login() {
JPanel loginPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(
0, 0, 1, 1, 0, 0,
GridBagConstraints.BASELINE_TRAILING,
GridBagConstraints.NONE,
new Insets(5, 5, 5, 5), 4, 6);
loginPanel.add(new JLabel("ID"), gbc);
gbc.gridy = 1;
loginPanel.add(new JLabel("Password"), gbc);
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.gridx = 1;
gbc.gridy = 0;
loginPanel.add(new JTextField("enter ID", 10), gbc);
gbc.gridy = 1;
loginPanel.add(new JPasswordField(6), gbc);
int result = JOptionPane.showConfirmDialog(
ui, loginPanel, "LogIn", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
// here a real app would check the results of the ID/password
cardLayout.show(ui, "loggedin");
}
}
Here is the complete example (an MCVE, as mentioned above).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BlockTheFrame {
private JComponent ui = null;
private CardLayout cardLayout;
BlockTheFrame() {
initUI();
}
public final void initUI() {
if (ui != null) {
return;
}
cardLayout = new CardLayout();
ui = new JPanel(cardLayout);
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JLabel login = new JLabel("Log in");
login.setFont(login.getFont().deriveFont(200f));
ui.add(login, "login");
ui.add(new JLabel("logged in"), "loggedin");
}
public void login() {
JPanel loginPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(
0, 0, 1, 1, 0, 0,
GridBagConstraints.BASELINE_TRAILING,
GridBagConstraints.NONE,
new Insets(5, 5, 5, 5), 4, 6);
loginPanel.add(new JLabel("ID"), gbc);
gbc.gridy = 1;
loginPanel.add(new JLabel("Password"), gbc);
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
gbc.gridx = 1;
gbc.gridy = 0;
loginPanel.add(new JTextField("enter ID", 10), gbc);
gbc.gridy = 1;
loginPanel.add(new JPasswordField(6), gbc);
int result = JOptionPane.showConfirmDialog(
ui, loginPanel, "LogIn", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
// here a real app would check the results of the ID/password
cardLayout.show(ui, "loggedin");
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BlockTheFrame o = new BlockTheFrame();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
o.login();
}
};
SwingUtilities.invokeLater(r);
}
}

Related

JFrame is not appearing consistently once JTable was added

I am currently trying to include a JTable to my JPanel. I was not having any problems with my code previously until I started to code the table. Sometimes when I run my program everything will appear, sometimes just the panels appear, and sometimes/majority of the time nothing will appear. I just don't understand why it is not consistent. There are no errors in the console. I have included below my ViewPage.java, Page.java, and Main.java.
`
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ViewPage extends Page implements ActionListener
{
JPanel panel1, panel2, panel3;
JLabel searchLabel, repairsLabel, dateLabel;
JButton goButton, recentButton, oldestButton, homeButton;
JComboBox dropDown;
JTextField textField;
JTable tabel;
JScrollPane scrollpane;
public ViewPage()
{
panel1 = new JPanel();
panel1.setBackground(Color.blue);
panel1.setBounds(0,0,1280,120);
panel2 = new JPanel();
panel2.setBackground(Color.green);
panel2.setBounds(0,120,1280,480);
panel3 = new JPanel();
panel3.setBackground(Color.red);
panel3.setBounds(0,600,1280,120);
//Panel 1 components
repairsLabel = new JLabel("Repairs");
repairsLabel.setFont(new Font("Serif", Font.BOLD, 50));
searchLabel = new JLabel("Search :");
searchLabel.setFont(new Font("Serif", Font.PLAIN, 25));
goButton = new JButton("GO");
goButton.setFocusable(false);
goButton.addActionListener(this);
textField = new JTextField();
String[] filters = {" ", "customerID", "First_Name", "Last_Name"};
dropDown = new JComboBox(filters);
dropDown.addActionListener(this);
panel1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 0);
gbc.weightx = 5.5;
gbc.gridx = 0;
gbc.gridy = 0;
panel1.add(repairsLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0.5;
gbc.gridx = 1;
gbc.gridy = 0;
panel1.add(searchLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.weightx = 3;
gbc.gridx = 2;
gbc.gridy = 0;
panel1.add(dropDown, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.ipadx = 100;
panel1.add(textField, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 100);
gbc.gridx = 4;
gbc.gridy = 0;
gbc.ipadx = 1;
panel1.add(goButton, gbc);
//Panel 2 components
panel2.setLayout(new GridBagLayout());
String[][] data = new String[50][8];
String[] headings = {"customer_ID", "Date", "First Name", "Last Name", "Phone #", "OS", "PC Type", "Problem"};
JTable table = new JTable(data, headings);
table.setEnabled(false);
table.setPreferredScrollableViewportSize(new Dimension(1000,400));
table.setFillsViewportHeight(true);
scrollpane = new JScrollPane(table);
panel2.add(scrollpane);
//Panel 3 componets
panel3.setLayout(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
dateLabel = new JLabel("Date Filter: ");
dateLabel.setFont(new Font("Serif", Font.PLAIN, 25));
recentButton = new JButton("Most Recent");
oldestButton = new JButton("Oldest");
homeButton = new JButton("Home");
gbc2.fill = GridBagConstraints.HORIZONTAL;
gbc2.insets = new Insets(1, 10, 1, 0);
gbc2.weightx = 5.5;
gbc2.gridx = 0;
gbc2.gridy = 0;
panel3.add(dateLabel, gbc);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == dropDown)
{
System.out.println(dropDown.getSelectedItem());
}
}
}
`
`
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public abstract class Page
{
private final static int pageWidth = 1280;
private final static int pageHeight = 720;
protected JFrame frame;
public Page()
{
frame = new JFrame();
frame.setTitle("Computer Repair Store");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(pageWidth, pageHeight);
frame.setLayout(null);
frame.setVisible(true);
}
public int getpageWidth()
{
return pageWidth;
}
public int getpageHeight()
{
return pageHeight;
}
}
`
`
public class Main {
public static void main(String[] args) {
ViewPage viewPage = new ViewPage();
}
}
`
Ouput:
enter image description here
This is what I am expecting to output which has only appeared 2-3 times out of the 50 times I have tried running the program.
enter image description here

How to Separate Panels in a JFrame to Separate Classes

I have this JFrame named MainFrame and I'm trying to separate each panel into it's own class. I tried and failed with some errors.
Please see the code that I tried. What failed and what did I get wrong?
public class MainFrame extends JFrame {
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private StartScreenPlayerPanel startScreenPlayerPanel;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
System.out.println(screenSize);
frame.setMinimumSize(new Dimension(screenSize.width/2, screenSize.height/2));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
startScreenPlayerPanel = new StartScreenPlayerPanel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, (screenSize.width * 2 / 3), (screenSize.height * 2 / 3));
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{1200, 0};
gbl_contentPane.rowHeights = new int[]{74, 0, 446, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblTitle = new JLabel("The Coin Game",SwingConstants.CENTER);
lblTitle.setFont(new Font("Arial", Font.PLAIN, (int)screenSize.width/30));
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.gridwidth = 2;
gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
gbc_lblTitle.anchor = GridBagConstraints.NORTH;
gbc_lblTitle.fill = GridBagConstraints.HORIZONTAL;
gbc_lblTitle.gridx = 0;
gbc_lblTitle.gridy = 0;
contentPane.add(lblTitle, gbc_lblTitle);
JPanel StartScreenBtnPanel = new JPanel();
GridBagConstraints gbc_StartScreenBtnPanel = new GridBagConstraints();
gbc_StartScreenBtnPanel.gridwidth = 0;
gbc_StartScreenBtnPanel.insets = new Insets(0, 0, 5, 0);
gbc_StartScreenBtnPanel.fill = GridBagConstraints.BOTH;
gbc_StartScreenBtnPanel.gridx = 0;
gbc_StartScreenBtnPanel.gridy = 1;
contentPane.add(StartScreenBtnPanel, gbc_StartScreenBtnPanel);
StartScreenBtnPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnAddPlayer = new JButton("Add Player");
btnAddPlayer.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnAddPlayer);
JButton btnStartGame = new JButton("Start Game");
btnStartGame.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnStartGame);
The code I'm trying to separate to a different Class
// JPanel tblPanel = new JPanel();
// GridBagConstraints gbc_tblPanel = new GridBagConstraints();
// gbc_tblPanel.gridwidth = 2;
// gbc_tblPanel.insets = new Insets(0, 0, 5, 0);
// gbc_tblPanel.fill = GridBagConstraints.BOTH;
// gbc_tblPanel.gridx = 0;
// gbc_tblPanel.gridy = 2;
// contentPane.add(tblPanel, gbc_tblPanel);
// tblPanel.setLayout(new BorderLayout(0, 0));
// table = new JTable();
// tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
// table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 16));
// table.setModel(new DefaultTableModel(
// new Object[][] {
// },
// new String[] {
// "New Player", "Initial Points"
// }
// ) {
// Class[] columnTypes = new Class[] {
// String.class, Integer.class
// };
// public Class getColumnClass(int columnIndex) {
// return columnTypes[columnIndex];
// }
// });
// table.getColumnModel().getColumn(0).setResizable(false);
// table.getColumnModel().getColumn(0).setMinWidth(14);
// tblPanel.add(table, BorderLayout.CENTER);
What I tried
At the end of MainFrame Class
contentPane.add(startScreenPlayerPanel, startScreenPlayerPanel.getSSPPConstraints());
}
public StartScreenPlayerPanel getStartScreenPlayerPanel() {
return startScreenPlayerPanel;
}
New Class - StartScreenPlayerPanel
public class StartScreenPlayerPanel extends JFrame {
MainFrame mainframe;
private JTable table;
private GridBagConstraints gbc_tblPanel = new GridBagConstraints();
public StartScreenPlayerPanel() {
JPanel tblPanel = new JPanel();
gbc_tblPanel.gridwidth = 2;
gbc_tblPanel.insets = new Insets(0, 0, 5, 0);
gbc_tblPanel.fill = GridBagConstraints.BOTH;
gbc_tblPanel.gridx = 0;
gbc_tblPanel.gridy = 2;
tblPanel.setLayout(new BorderLayout(0, 0));
table = new JTable();
tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 16));
table.setModel(new DefaultTableModel(new Object[][] {}, new String[] { "New Player", "Initial Points" }) {
Class[] columnTypes = new Class[] { String.class, Integer.class };
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
});
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(0).setMinWidth(14);
tblPanel.add(table, BorderLayout.CENTER);
}
public GridBagConstraints getSSPPConstraints(){
return gbc_tblPanel;
}
}
I'm trying to seperate each panel to it's own class
public class StartScreenPlayerPanel extends JFrame {
Ok, so why are you extending JFrame?
If you want to add a panel to the main frame then you extend JPanel:
public class StartScreenPlayerPanel extends JPanel {
Now because your class "is a" JPanel, you just set the layout manager of the panel and add components to it.
public StartScreenPlayerPanel()
{
setLayout(new BorderLayout());
table = new JTable();
table.setModel( ... );
add(table.getTableHeader(), BorderLayout.NORTH);
add(table, BorderLayout.CENTER);
}
There is no need for the getSSPPConstraints() method in this class. The "StartScreenPlayerPanel" doesn't know or care how the panel is used. It only worries about the layout of the components in its own class.
The result is a JPanel with a JTable added to the JPanel.
Note: typically when using a JTable you would use:
//add(table.getTableHeader(), BorderLayout.NORTH);
//add(table, BorderLayout.CENTER);
add(new JScrollPane(table), BorderLayout.CENTER);
The scrollpane will automatically add the table header to itself.
Now in your main class you add the panel to the content pane:
//contentPane.add(startScreenPlayerPanel, startScreenPlayerPanel.getSSPPConstraints());
GridBagConstraints gbc_playerPanel = new GridBagConstraints();
gbc_playerPanel.gridwidth = 2;
gbc_playerPanel.insets = new Insets(0, 0, 5, 0);
gbc_playerPanel.fill = GridBagConstraints.BOTH;
gbc_playerPanel.gridx = 0;
gbc_playerPanel.gridy = 2;
contentPane.add(startScreenPlayeerPanel, gbc_playerPanel).
That is the constraints are the property of the class that adds the panel to the content panel.

Need help making button relay information

Okay, so I have made a GUI with some input boxes and a combo box. I am wondering how I would go about having a listener know when the button is pressed then relay all the information in the imput boxes and combo box into different parts of the script...
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class dogedice extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JComboBox combo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dogedice frame = new dogedice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public dogedice() {
setTitle("DogeDice Bot");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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.WEST);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
//Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
JLabel userTag = new JLabel("Username:");
GridBagConstraints gbc_userTag = new GridBagConstraints();
gbc_userTag.insets = new Insets(0, 0, 0, 5);
gbc_userTag.anchor = GridBagConstraints.EAST;
gbc_userTag.gridx = 0;//Here are your x + y coords
gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
panel.add(userTag, gbc_userTag);
//Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
textField = new JTextField();
GridBagConstraints gbc_Username = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel startTag = new JLabel("Starting Bid:");
GridBagConstraints gbc_startTag = new GridBagConstraints();
gbc_startTag.insets = new Insets(0, 0, 0, 5);
gbc_startTag.anchor = GridBagConstraints.EAST;
gbc_startTag.gridx = 0;
gbc_startTag.gridy = 2;
panel.add(startTag, gbc_startTag);
textField = new JTextField();
GridBagConstraints gbc_StartBid = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 2;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel multTag = new JLabel("Multiplier:");
GridBagConstraints gbc_multTag = new GridBagConstraints();
gbc_multTag.insets = new Insets(0, 0, 0, 5);
gbc_multTag.anchor = GridBagConstraints.EAST;
gbc_multTag.gridx = 0;
gbc_multTag.gridy = 3;
panel.add(multTag, gbc_multTag);
textField = new JTextField();
GridBagConstraints gbc_Multiplier = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel minTag = new JLabel("Min Remaining:");
GridBagConstraints gbc_minTag = new GridBagConstraints();
gbc_minTag.insets = new Insets(0, 0, 0, 5);
gbc_minTag.anchor = GridBagConstraints.EAST;
gbc_minTag.gridx = 0;
gbc_minTag.gridy = 4;
panel.add(minTag, gbc_minTag);
textField = new JTextField();
GridBagConstraints gbc_MinRemaining = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 4;
panel.add(textField, gbc_textField);
textField.setColumns(10);
textField = new JTextField();
GridBagConstraints gbc_Password = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel passTag = new JLabel("Password:");
GridBagConstraints gbc_passTag = new GridBagConstraints();
gbc_passTag.insets = new Insets(0, 0, 0, 5);
gbc_passTag.anchor = GridBagConstraints.EAST;
gbc_passTag.gridx = 0;
gbc_passTag.gridy = 1;
panel.add(passTag, gbc_passTag);
textField = new JTextField();
GridBagConstraints gbc_Odds = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 5;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel oddsTag = new JLabel("Odds %:");
GridBagConstraints gbc_oddsTag = new GridBagConstraints();
gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
gbc_oddsTag.anchor = GridBagConstraints.EAST;
gbc_oddsTag.gridx = 0;
gbc_oddsTag.gridy = 5;
panel.add(oddsTag, gbc_oddsTag);
textField = new JTextField();
GridBagConstraints gbc_ComboBox = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 6;
panel.add(textField, gbc_textField);
textField.setColumns(10);
//This is the Combo Box
combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
combo.addActionListener(this);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.fill = GridBagConstraints.HORIZONTAL;
gbc_list.gridx = 1;
gbc_list.gridy = 7;
panel.add(combo, gbc_list);
JLabel maxTag = new JLabel("MaxBet:");
GridBagConstraints gbc_maxTag = new GridBagConstraints();
gbc_maxTag.insets = new Insets(0, 0, 0, 5);
gbc_maxTag.anchor = GridBagConstraints.EAST;
gbc_maxTag.gridx = 0;
gbc_maxTag.gridy = 6;
panel.add(maxTag, gbc_maxTag);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
JButton btnConfirm = new JButton("Turn Up");
panel_1.add(btnConfirm);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea("Current Balance");
textArea.setColumns(1);
scrollPane.setViewportView(textArea);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textAreal = new JTextArea("Input bot information here...");
textArea.setColumns(20);
scrollPane.setViewportView(textArea);
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == combo) {
System.out.println(combo.getSelectedIndex()+1);
}
}
}
It's quite straightforward to add an ActionListener to a JButton.
// ...
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(this);
panel_1.add(btnConfirm);
// ...
Because you'll want to know when the button is triggering the callback, like so:
private JButton btnConfirm;
This way, you'll be able to tell when it's that button that triggered the actionListener() method:
if (event.getSource() == btnConfirm) {
// Handle "Turn Up" button press here
}
Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
Essentially you need to register an ActionListener with your button...
There are a number of ways you might be able to achieve this...
You Could
Use the more traditional, purpose class...
public class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
if ("Turn Up".evt.getActionCommand()) {
// Handle Turn Up...
}
}
}
In this context, you'll be required to provide a reference to the component you want to modify so that the ActionHandler can interact with it, personally, this is best done via an interface, but that's just me...
public class ActionHandler implements ActionListener {
private dogedice dice;
public ActionHandler(dogedice dice) {
this.dice = dice;
}
public void actionPerformed(ActionEvent evt) {
//...
}
}
The benefit of this is you can plug an play the action handler, changing what the action does depending on your needs. If you use an interface instead of an implementation reference, you further decouple the action from the program
You Could
Use use an anonymous class
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// handle turn up action...
}
});
The benefit to this is, you don't end up with "another" class, the ActionListener can reference all the internal fields of the parent class and, because you've attached it directly, you can assume that the only thing that is going to generate the ActionEvent is the btnConfirm button.
The downside is you lose the flexibility to change how the action is handled without physically modifying the code
You Could
Take advantage of the Actions API, this is a little like the first option, in that you (should normally) create another class specifically designed to handle the "Turn Up" event, but these are self contained entities. That is, they carry all the information required to configure the UI element and perform the required action when triggered.
This is really good where the action may be repeated in the UI via menus, buttons or key strokes

Increasing distance from top of JPanel

I'm trying to increase the distance of my JButtons from the top of my Panel to make it more visually appealing, i've tried using an invisible button but have had no luck.
public class SimpleBorder {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Border etched = (Border) BorderFactory.createEtchedBorder();
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
JTextArea text = new JTextArea(10, 40);
JScrollPane scrol = new JScrollPane(text);
JScrollPane scrol2 = new JScrollPane(list);
JPanel panel= new JPanel();
panel.add(scrol2,BorderLayout.WEST);
panel.add(scrol, BorderLayout.EAST);
panel.setBorder(etched);
frame.add(panel);
frame.setVisible(true);
}
}
Any ideas ?
The key basically lies, in the fact, that the component doesn't knows it's actual size, till frame.pack() won't be called. Hence after this I am performing this calculation, to determine how much empty space to put for Border and again calling frame.pack() to repack() everything after putting the Border.
Please do have a look at this example, and see if this suite your needs :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private GridBagConstraints gbc;
public MainMenu() {
gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
}
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout());
menuPanel = new JPanel(new GridBagLayout());
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
addComp(menuPanel, playButton, 0, 0, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, instructionButton, 0, 1, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, scoreboardButton, 0, 2, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
addComp(menuPanel, exitButton, 0, 3, 1, 1, 1.0, 0.20,
GridBagConstraints.HORIZONTAL);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() - (contentPane.getHeight() / 4),
20, 5, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp,
int gridx, int gridy,
int gridwidth, int gridheight,
double weightx, double weighty,
int fill) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.fill = fill;
panel.add(comp, gbc);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
Here is the output :
EDIT 1 :
Moreover, if you will use GridLayout instead of using GridBagLayout for the MainMenu, then I guess the results will be more promising. Please have a look at this example for that change :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new GridBagLayout());
menuPanel = new JPanel(new GridLayout(0, 1, 5, 5));
menuPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
menuPanel.add(playButton);
menuPanel.add(instructionButton);
menuPanel.add(scoreboardButton);
menuPanel.add(exitButton);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() -
(contentPane.getHeight() -
(3 * menuPanel.getHeight())),
20, 0, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
EDIT 2 :
Another variant is looking much better, though, this time, the base JPanel is using GridLayout and the MenuPanel is using GridBagLayout. Please have a look at this example :
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton playButton;
private JButton instructionButton;
private JButton scoreboardButton;
private JButton exitButton;
private JPanel menuPanel;
private GridBagConstraints gbc;
public MainMenu() {
gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.anchor = GridBagConstraints.CENTER;
}
private void displayGUI() {
JFrame frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new GridLayout(1, 1, 5, 2));
menuPanel = new JPanel(new GridBagLayout());
menuPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
menuPanel.setOpaque(true);
menuPanel.setBackground(Color.BLACK);
playButton = new JButton("Play");
instructionButton = new JButton("Instructions");
scoreboardButton = new JButton("Scoreboard");
exitButton = new JButton("Exit");
addComp(menuPanel, playButton, 0, 0, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, instructionButton, 0, 1, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, scoreboardButton, 0, 2, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
addComp(menuPanel, exitButton, 0, 3, 1, 1, 1.0, 0.10,
GridBagConstraints.CENTER);
contentPane.add(menuPanel);
frame.setContentPane(contentPane);
frame.pack();
contentPane.setBorder(
BorderFactory.createEmptyBorder(
contentPane.getHeight() -
(contentPane.getHeight() -
(2 * menuPanel.getHeight()) + 100),
20, 2, 20));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp,
int gridx, int gridy,
int gridwidth, int gridheight,
double weightx, double weighty,
int fill) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.fill = fill;
panel.add(comp, gbc);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new MainMenu().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

gridbagconstraints not working

I am using gridbaglayout to show a JLabel (number of thumbnails ) and some thumbnails whenever I add the thumbnail to the Jpanel with gridbaglayout it shows up in the center ignoring gridy values. The gridx values are working correctly but gridy values are completely ignored...
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.*;
public class grid {
private JFrame frame = new JFrame();
private JLabel a = new JLabel("Welcome to PhotoAlbum55");
/**
* Create the frame.
*/
public grid() {
createAndShowGUI();
}
private void addComponentsToPane(Container pane) {
SpringLayout layout = new SpringLayout();
pane.setLayout(layout);
layout.putConstraint(SpringLayout.WEST, a, 60, SpringLayout.WEST, pane);
layout.putConstraint(SpringLayout.NORTH, a, 0, SpringLayout.NORTH, pane);
a.setFont(new Font("Segoe UI", Font.BOLD, 20));
pane.add(a);
JPanel photoPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
photoPanel.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
JScrollPane photoScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
photoScroll.setViewportView(photoPanel);
pane.add(photoScroll);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 15;
gbc.fill = GridBagConstraints.HORIZONTAL;
JLabel photo = new JLabel();
Image img = new ImageIcon("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg").getImage();
Image newimg = img.getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH);
ImageIcon newIcon = new ImageIcon(newimg);
photo.setIcon(newIcon);
gbl.setConstraints(photo, gbc);
photoPanel.add(photo);
JLabel photo1 = new JLabel();
Image img1 = new ImageIcon("C:\\Users\\Public\\Pictures\\Sample Pictures\\Lighthouse.jpg").getImage();
Image newimg1 = img1.getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH);
ImageIcon newIcon1 = new ImageIcon(newimg1);
photo1.setIcon(newIcon1);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.ipadx = 15;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbl.setConstraints(photo1, gbc);
photoPanel.add(photo1);
// photoPanel.setPreferredSize(new Dimension(900, 900));
photoScroll.setPreferredSize(new Dimension(500, 500));
layout.putConstraint(SpringLayout.WEST, photoScroll, 60, SpringLayout.WEST, a);
layout.putConstraint(SpringLayout.NORTH, photoScroll, 100, SpringLayout.NORTH, a);
}
private void createAndShowGUI() { // Creating the GUI...
frame.getContentPane().setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("PhotoAlbum55");
// Set up the content pane.
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setSize(690, 622);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setVisible(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new grid();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Both images are on the same y co-ordinate so the application is behaving as intended. On the other hand, the x co-ordinates differ so you need to set
gbc.weightx = 1;
for them to be positioned. If you need to add images to the top of the panel, they will need to be anchored there and set the weight along the y axis:
gbc.anchor = GridBagConstraints.NORTH;
gbc.weighty = 1;

Categories