How to format vertically with GridBagLayout - java

I am making a project that uses a box and a JComboBox and want to use GridBagLayout. I want the combo box at the top center of the screen, then the Box with a JTextArea inside at the center. This is my code so far:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
/**comboBoxFrame Constructor
* Takes Mouse Event Input From User
* Based On Option Chosen By User From Dropdown, Displays Corresponding information, Taken From birtdayCaclulator.java
*/
#SuppressWarnings("serial")
public class comboBoxFrame extends JFrame {
private final JComboBox<String> classComboBox;
private JTextArea outputBox;
private static final String[] names = {
"-Select-",
"Age Summary",
"Zodiac Sign",
"Birth Stone",
"Generation",
"Day of Week",
"Lucky Number",
"Milestones",
"First Presidential Election Vote",
"Days Since Last Birthday",
"Days Until Next Birthday",
"Animal Years Summary",
"Other Planet Age Summary",
"Days After Milestones Summary",
"Birthday Summary",
"Help"
};
private static final String[] output = {
"Output will appear here",
CreateDriver.bday.ageSummary(),
CreateDriver.bday.getZodiacSign(),
CreateDriver.bday.getBirthStone(),
CreateDriver.bday.getGeneration(),
CreateDriver.bday.getDayOfWeek(),
CreateDriver.bday.getLuckyNum(),
CreateDriver.bday.getMileStones(),
CreateDriver.bday.getFirstPresElectionVote(),
CreateDriver.bday.getDaysSinceLastBday(),
CreateDriver.bday.getDaysTillNextBday(),
CreateDriver.bday.animalYearsSummary(),
CreateDriver.bday.otherPlanetAgeSummary(),
CreateDriver.bday.getDaysAfterMilestonesSummary(),
CreateDriver.bday.toString(),
CreateDriver.bday.getHelp()
};
public comboBoxFrame() {
super("Birthday Calculator");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Box box = new Box(BoxLayout.Y_AXIS);
outputBox = new JTextArea("Output will appear here", 20, 50);
box.add(outputBox, gbc);
classComboBox = new JComboBox<String>(names);
classComboBox.setMaximumRowCount(5);
classComboBox.addItemListener(
new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
outputBox.setText(output[classComboBox.getSelectedIndex()]);
}
}
}
);
add(classComboBox, gbc);
outputBox = new JTextArea("Output will appear here");
add(outputBox, gbc);
}
}
It currently prints the ComboBox and Box next to each other at the center Y Axis. Does anyone know what I should change to fix this?

Related

Generate non-repeating fortunes for my JAVA fortune teller program?

//FortuneTellerFrame.java
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.event.ActionEvent;
import java.util.Random;
public class FortuneTellerFrame extends JFrame
{
JPanel master, panel1, panel2, panel3;
JLabel image, heading, textArea;
ImageIcon logo;
JTextArea screen;
JScrollPane scroller;
JButton quit, generate;
ActionListener clicker, quiter;
ArrayList<String>fortuneDB=new ArrayList<>();
public FortuneTellerFrame()
{
super("Fortune Spitter");
master = new JPanel();
panel1();
panel2();
panel3();
fortuneHolder();
//add panels to master
master.setLayout(new BorderLayout());
master.add(panel1, BorderLayout.NORTH);
master.add(panel3, BorderLayout.SOUTH);
master.add(scroller, BorderLayout.CENTER);
//master adjustments
add(master);
setSize(750,750);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public void panel1()
{
panel1=new JPanel();
heading = new JLabel("Harry Potter Fortune Teller");
heading.setFont(new Font("Courier New", Font.ITALIC, 25));
logo=new ImageIcon("\\Users\\x\\Desktop\\harry.jpg");
image=new JLabel(logo);
panel1.add(image);
panel1.add(heading);
}
public void panel2()
{
panel2=new JPanel();
screen=new JTextArea(50,50);
screen.setEditable(false);
scroller=new JScrollPane(screen);
scroller.setVisible(true);
}
public void panel3()
{
panel3=new JPanel();
//fortune-spitter
generate = new JButton("Spit Fortune");
generate.setFont(new Font("Times New Roman", Font.BOLD, 20));
generate.addActionListener((ActionEvent ae) ->
//generate fortune button logic
//Please suggest a way in which I can generate a new fortune each time without having to repeat the old fortune again.
{
int currentRnd;
int previousRnd=0;
Random rnd = new Random();
do
{
currentRnd=rnd.nextInt(12);//there are 12 fortunes
}
while(currentRnd== previousRnd);
String fortune = fortuneDB.get(currentRnd);
int spot =screen.getCaretPosition();
screen.insert(fortune+"\n", spot);
currentRnd = previousRnd;
//I am unable to write a loop that generates a new fortune each time I hit generate.
});
panel3.add(generate);
//quitter
quit=new JButton("Quit"); //Text inside the button
quit.setFont(new Font("Times New Roman", Font.BOLD, 20));
quit.addActionListener((ActionEvent ae) ->
{
System.exit(0);
});
panel3.add(quit);
//in the panel3 I want to output fortunes to the JTextArea and I do not want to repeat the same fortune twice. I tried some stuff on Google, but nothing helped.
}
private void fortuneHolder()
{
fortuneDB.add("You will get a good GPA");
fortuneDB.add("Your GPA does not mean anything!");
fortuneDB.add("Please catch up on CPII labs");
fortuneDB.add("Don't turn assignments in for points, make sure you gain the knowledge");
fortuneDB.add("You will get a good co-op");
fortuneDB.add("Click generate fortune to discover your true fortune");
fortuneDB.add("The weather will soon be nice");
fortuneDB.add("Buy a PowerBall");
fortuneDB.add("Here are your lucky numbers 17-19-23-50-51");
fortuneDB.add("If you win the Powerball dropuut of school");
fortuneDB.add("Snow Day Coming");
fortuneDB.add("Do Not waste your time");
}
}//end of FrameClass
//FortuneTellerViewer.java
import javax.swing.JFrame;
public class FortuneTellerViewer
{
public static void main(String[]args)
{
JFrame frame = new FortuneTellerFrame();
frame.setVisible(true);
}
}
Start by using Collections.shuffle to randomise the list
Then when the button is clicked, you would remove the first element from the list (List#remove(int)) until there are no more elements in the list.
If you need the original List, you could use a secondary list, this way, you could re-generate the "pick list" once you run out
Conceptually, the idea you're after is something like...
import java.util.ArrayList;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
new Test();
}
private ArrayList<String> fortuneDB = new ArrayList<>();
public Test() {
String last = null;
for (int index = 0; index < 10; index++) {
// This makes sure that the last fortune isn't
// the first on the next cycle...
do {
makeFortunes();
} while (fortuneDB.get(0).equals(last));
while (fortuneDB.size() > 0) {
last = fortuneDB.remove(0);
System.out.println(last);
}
System.out.println("----------");
}
}
protected void makeFortunes() {
fortuneDB = new ArrayList<>();
fortuneDB.add("You will get a good GPA");
fortuneDB.add("Your GPA does not mean anything!");
fortuneDB.add("Please catch up on CPII labs");
fortuneDB.add("Don't turn assignments in for points, make sure you gain the knowledge");
fortuneDB.add("You will get a good co-op");
fortuneDB.add("Click generate fortune to discover your true fortune");
fortuneDB.add("The weather will soon be nice");
fortuneDB.add("Buy a PowerBall");
fortuneDB.add("Here are your lucky numbers 17-19-23-50-51");
fortuneDB.add("If you win the Powerball dropuut of school");
fortuneDB.add("Snow Day Coming");
fortuneDB.add("Do Not waste your time");
Collections.shuffle(fortuneDB);
}
}

Returning value from Action Performed for use in other class

i have the following code for creating a drop down menu that contains certain ranks ,
i need to be able to get whatever rank the user has selected from the menu so i can use the answer in other classes
package userInterface;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class gui extends JFrame implements ActionListener {
String[] messageStrings = { "RANK 1", "RANK 2", "RANK 3" };
JComboBox cmbMessageList = new JComboBox(messageStrings);
JLabel user = new JLabel();
JLabel item1;
String user_rank;
public static void main(String[] args) {
gui newguiGui = new gui();
newguiGui.setVisible(true);
}
public gui() {
setLayout(new FlowLayout());
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cmbMessageList.setSelectedIndex(1);
cmbMessageList.addActionListener(this);
add(cmbMessageList);
add(user);
setLayout(new FlowLayout());
setLayout(new FlowLayout());
item1 = new JLabel("enter the street you are on here");
item1.setToolTipText("In this box you enter if you are: pre flop, flop, turn or river");
// adding items to the interface
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == cmbMessageList) {
JComboBox cb = (JComboBox) e.getSource();
String msg = (String) cb.getSelectedItem();
switch (msg) {
case "RANK 1":
user_rank = "RANK 1";
break;
case "RANK 2":
user_rank = "RANK 2";
break;
case "RANK 3":
user_rank = "RANK 3";
break;
}
}
}
}
thanks in advance
You can make your String user_rank public if your other class is not in the same package:
public String user_rank;
Then you can access it with gui.user_rank.
Also:
Use userRank instead to follow Java naming conventions.
Use Gui for class name for same reason as above.
Immediately replace e.getSource() == cmbMessageList with e.getSource().equals(cmbMessageList).
You don't need to call setLayout(new FlowLayout()) 3 times.
Another approach would be to add a (public or default access) method which would return user_rank and have the other class call that method. In this case you can make your variable even private.
You can probably store it in a variable. And use it by calling a getter method.

How to update the cells of a table from a combobox?

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import net.java.dev.designgridlayout.DesignGridLayout;
import java.io.*;
import net.java.dev.designgridlayout.Tag;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
class table1
{
JFrame JF;
Container C;
JPanel JP;
JLabel creditLabel;
JComboBox credit;
String[] Credit = {"Vasan Phalke", "Pansare", "Anil Kg", "Suresh"};
String[] Names = {"Name", "Qty", "Rate/ Kg", "Rate/Dzn.", "Total Amt."};
JTable table;
DefaultTableModel model;
JScrollPane scrollPane;
public table1()
{
JF = new JFrame();
JP = new JPanel();
C= JF.getContentPane();
JF.pack();
JF.setLocationRelativeTo(null);
JF.setVisible(true);
DesignGridLayout layout = new DesignGridLayout(C);
creditLabel = new JLabel("Credit");
credit = new JComboBox<String>(Credit);
model = new DefaultTableModel(Names,5);
table =new JTable(model){#Override
public boolean isCellEditable(int arg0, int arg1)
{
return true;
}
};
scrollPane= new JScrollPane(table);
layout.row().grid(creditLabel).add(credit);
layout.emptyRow();
layout.row().grid().add(table);
C.add(JP);
}
public static void main(String args[])
{
new table1();
}
}
By clicking on the value of combobox, it should appear in the name column of the table, and what changes should be made to the table for automatic calculation, ie, when i enter qty and rate, total amount should automatically be calculated.
How all these things can be done, please help.
Thanks in advance.
Read the section from the Swing tutorial on How to Use Tables
The tutorial shows you how to use a combo box as an editor for a column in a table. This is what you should be doing instead of having a separate combo box.
To calculate the amount, you need to create a custom TableModel and override the setValueAt() method. Whenever the quantity or rate changes you recalculate the amount.

Blank JFrame and No JPanel appeared but already added

Can anyone help me? Whenever I ran the codes below, it always returns a blank frame, I don't know where I did wrong. Can you guys help me debug this? I already added the components to the panel, and the panel to the frame, but still it returns a blank output.
Here is the output I'm getting:
While this is what is required.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.BoxLayout;
import java.awt.GridLayout;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JRadioButton;
/**
*
* #author Chareux
*/
//Declaring Variables
public class TestUI {
private JFrame frm_main;
private JPanel sr_pnl;
private JLabel sr_lbl;
private JLabel sr_lbl2;
private JLabel ret_optn_lbl;
private JLabel ret_rsn_lbl;
private ButtonGroup ret_ops;
private JTextField sr_txtnum;
private JTextField sr_ret_txtrsn;
private JButton sr_start;
private JRadioButton ret_optn_rdbn_y;
private JRadioButton ret_optn_rdbn_n;
public TestUI(){
start();
}
public void start(){
//Creating the JFrame
frm_main = new JFrame("Service Desk SR Tool");
frm_main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm_main.setSize(500,450);
frm_main.setLocationRelativeTo(null);
frm_main.setResizable(false);
frm_main.setVisible(true);
// the Panel
sr_pnl = new JPanel();
//Components
sr_lbl = new JLabel("SERVICE DESK SR TIMER!");
sr_lbl2 = new JLabel("SR number: ");
sr_txtnum = new JTextField("Enter SR number here..",20);
ret_optn_lbl = new JLabel("Returning Ticket?");
ret_optn_rdbn_y = new JRadioButton("Yes");
ret_optn_rdbn_n = new JRadioButton("No");
ret_rsn_lbl = new JLabel("Reason: ");
sr_ret_txtrsn = new JTextField("Enter Reason number here..",20);
sr_start = new JButton("START!");
//adding the Components to the panel
sr_pnl.add(sr_lbl);
sr_pnl.add(sr_lbl2);
sr_pnl.add(sr_txtnum);
sr_pnl.add(ret_optn_lbl);
sr_pnl.add(ret_optn_rdbn_y);
sr_pnl.add(ret_optn_rdbn_n);
sr_pnl.add(ret_rsn_lbl);
sr_pnl.add(sr_ret_txtrsn);
sr_pnl.add(sr_start);
frm_main.add(sr_pnl,BorderLayout.CENTER);
//ButtonGroup for the radio button
ret_ops = new ButtonGroup();
ret_ops.add(ret_optn_rdbn_y);
ret_ops.add(ret_optn_rdbn_n);
}
public static void main(String[] args) {
new TestUI();
}
}
I'd recommend to use a nested or compound layout for this task. See further tips in comments in the source.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class SRTool {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new GridLayout(0,1,6,6));
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
// show the BG
gui.setBackground(Color.CYAN);
// center the label text
gui.add(new JLabel(
"Service Desk SR Tool", SwingConstants.CENTER));
// create a lyout that can center multiple components
FlowLayout layout = new FlowLayout(FlowLayout.CENTER,5,5);
JPanel srPanel = new JPanel(layout);
gui.add(srPanel);
srPanel.add(new JLabel("SR:"));
srPanel.add(new JTextField(8));
JPanel returnTicketPanel = new JPanel(layout);
gui.add(returnTicketPanel);
returnTicketPanel.add(new JLabel("Returning Ticket?"));
returnTicketPanel.add(new JCheckBox());
JPanel reasonPanel = new JPanel(layout);
gui.add(reasonPanel);
reasonPanel.add(new JLabel("Reason:"));
reasonPanel.add(new JTextField(14));
JPanel buttonPanel = new JPanel(layout);
gui.add(buttonPanel);
buttonPanel.add(new JButton("Start!"));
JFrame f = new JFrame("Demo");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See https://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Add frm_main.validate() in the end of start()
public void start(){
/*
...
Same As Above
...
*/
frm_main.add(sr_pnl,BorderLayout.CENTER);
//ButtonGroup for the radio button
ret_ops = new ButtonGroup();
ret_ops.add(ret_optn_rdbn_y);
ret_ops.add(ret_optn_rdbn_n);
frm_main.validate(); // Add this line ******
}

why doesn't my itemlistener always trigger

enter image description hereI'm a new programmer and I'm working on a text adventure that uses dropdown boxes (choice) as an input device. I have an itemListener on the first box that populates the members of the 2nd with the members that can be added. The player is then allowed to click the submit button and the first box is reset to the first item on the list and the second box is supposed to be cleared. When I run the program, the first time it reacts exactly as planned. The 2nd time I try to input something using the drop down boxes, the dropdown box doesn't respond. I put a marker inside the itemListener to see if it was even triggering to find out that it wasn't. I feel like I've tweeked the program in every way imaginable but I have no idea what is causing this issue. If I toggle between the items in the drop down box a few times the itemListener starts to respond again.
This is a representation of my issue I threw together.
import java.awt.Choice;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
public class gui implements ActionListener
{
private static JTextPane outputField = new JTextPane();
private static JPanel mainPanel = new JPanel(new GridBagLayout());
private Choice commandDropDown = new Choice();
private Choice itemDropDown = new Choice();
private JButton submitButton = new JButton();
public gui()
{
JFrame frame = new JFrame("test");
mainPanel.setSize(450,585);
commandDropDown = buildCommandBox(commandDropDown);
commandDropDown.setBounds(100, 15, 100, 40);
itemDropDown.setBounds(200, 15, 100, 40);
submitButton.setText("submit");
submitButton.setBounds(15, 15, 100, 40);
submitButton.addActionListener(this);
frame.add(commandDropDown);
frame.add(itemDropDown);
frame.add(submitButton);
frame.setResizable(false);
frame.pack();
frame.setSize(300, 300);
//frame.setLayout(null);
//frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
itemDropDown.removeAll();
commandDropDown.select(0);
}
private Choice buildCommandBox(Choice custoChoi)
{
final Choice c = new Choice();
c.addItem("choices");
c.addItem("Option1");
c.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ie)
{
System.out.println("the action event for the command"
+ "box is working.");
if(c.getSelectedItem().equals("Option1"))
{
itemDropDown.addItem("things");
itemDropDown.addItem("stuff");
}
}
});
return c;
}
}
Hopefully these pictures clear up any confusion about my post.
http://imgur.com/a/h9oOX#0
In my opinion, your buildCommandBox( Choice custoChoi) is wrong, it should be something like that:
private Choice buildCommandBox(final Choice custoChoi) {
custoChoi.addItem("choices");
custoChoi.addItem("Option1");
custoChoi.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
System.out.println("the action event for the command" + "box is working.");
if (custoChoi.getSelectedItem().equals("Option1")) {
itemDropDown.addItem("things");
itemDropDown.addItem("stuff");
}
}
});
return custoChoi;
}
I would recommand to use JComboBox instants of Choice, if Swing is allowed.

Categories