I'm new to JTable, or GUI for that matter, but i had been given an assignment of building a receipt program inside a GUI. I manage to get the basic things work, but my table looks awful. I need help on how to display the table properly
public static void main (String[] args)
{
ArrayList <item> lol= new ArrayList <item>();
item ayam = new item("ayam",5678);
item kambing= new item("kambing",5014);
item buaya= new item("buaya",3000);
item bocoranquiz= new item("bocoranquiz",5000);
lol.add(ayam);
lol.add(kambing);
lol.add(buaya);
lol.add(bocoranquiz);
JFrame frame= new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 0));
frame.setSize(1000, 1000);
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
String date = sdf.format(new Date());
JComboBox combo1= new JComboBox();
combo1.setPreferredSize(new Dimension(10, 10));
combo1.addItem(ayam.getname());
combo1.addItem(kambing.getname());
combo1.addItem(buaya.getname());
combo1.addItem(bocoranquiz.getname());
JLabel label1= new JLabel("Invoice no: ");
JLabel label2= new JLabel("Invoice Date : " + date);
JLabel label3= new JLabel("Item name " );
JLabel label4= new JLabel("Item Price ");
JLabel label5= new JLabel("Item Quantity : ");
JPanel panel1= new JPanel ();
panel1.setLayout(new GridLayout(3,0));
panel1.add(label1);
panel1.add(label2);
class inputListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JComboBox<String> combo= (JComboBox<String>) event.getSource();
selected= (String) combo.getSelectedItem();
alpha=10;
if (selected.equals("ayam"))
{
alpha=5678;
}
else if (selected.equals("kambing"))
{
alpha=5014;
}
else if (selected.equals("buaya"))
{
alpha=3000;
}
else if (selected.equals("bocoranquiz"))
{
alpha=5000;
}
label3.setText("Item name " + selected);
label4.setText("Item quantity " + alpha);
}
}
ActionListener inputAct = new inputListener();
combo1.addActionListener(inputAct);
panel1.add(combo1);
JTextField tf = new JTextField();
JButton adda = new JButton("Add");
String[] columnNames= {"Name","Price","Quantity","Total"};
DefaultTableModel tablemodel= new DefaultTableModel(columnNames,0);
JTable table = new JTable(tablemodel);
JScrollPane scrollPanel = new JScrollPane(table);
class inputListener2 implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
quantity= Integer.parseInt(tf.getText());
double total= alpha * quantity;
Object[] data= {selected,alpha,quantity,total};
tablemodel.addRow(data);
}
ActionListener inputAct2 = new inputListener2();
adda.addActionListener(inputAct2);
JPanel panel2= new JPanel();
panel2.setLayout(new GridLayout(10,0));
panel2.add(label3);
panel2.add(label4);
panel2.add(label5);
panel2.add(tf);
panel2.add(adda);
panel2.add(scrollPanel);
frame.add(panel1);
frame.add(panel2);
frame.setVisible(true);
}
Your code is a bit of mess, but, the basic problem is your setting your GridLayout with to many rows, for example
frame.setLayout(new GridLayout(3, 0));
should be
frame.setLayout(new GridLayout(2, 0));
since you're only adding 2 components to the frame
Equally,
panel2.setLayout(new GridLayout(10, 0));
should probably be
panel2.setLayout(new GridLayout(6, 0));
Remember, a GridLayout will divide the container into equal sections, even if there is nothing contained within the row/column.
You may also want consider using a different layout manager, like GridBagLayout, or a combination of layouts depending on your basic needs.
See How to use GridBagLayout for more details.
Related
As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);
I tried to do this from stackoverflow:
adding multiple jPanels to jFrame
But that didn't seem to work out like in the example, could anyone tell me what im doing wrong?
Im trying to add multiple JPanels with each their own sizes to the JFrame. I was also hoping it was possible to give each JPanel specific sizes and ability to put them on the exact spot i want.
Picture of what i try to make:
This is my code so far:
public ReserveringenGUI(ReserveringController controller) {
this.controller = new ReserveringController();
makeFrame();
}
public void makeFrame() {
JFrame frame1 = new JFrame();
frame1.setTitle("Reserveringen");
frame1.setSize(800, 500);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
JPanel willekeurigPanel = new JPanel();
willekeurigPanel.setSize(400, 500);
willekeurigPanel.setBackground(Color.YELLOW);
willekeurigPanel.setVisible(true);
JPanel overzichtPanel = new JPanel();
overzichtPanel.setSize(400, 500);
overzichtPanel.setBackground(Color.red);
overzichtPanel.setVisible(true);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
DateFormatter df = new DateFormatter(format);
JFormattedTextField dateBeginField = new JFormattedTextField(df);
dateBeginField.setPreferredSize(new Dimension(250, 20));
dateBeginField.setValue(new Date());
JFormattedTextField dateEndField = new JFormattedTextField(df);
dateEndField.setPreferredSize(new Dimension(250, 20));
dateEndField.setValue(new Date());
JTextField klantnummer = new JTextField();
klantnummer.setPreferredSize(new Dimension(250, 20));
JTextField artikelnummer = new JTextField();
artikelnummer.setPreferredSize(new Dimension(250, 20));
JLabel dateBeginLabel = new JLabel("Begin Datum ");
JLabel dateEndLabel = new JLabel("Eind datum: ");
JLabel klantID = new JLabel("Klant nummer: ");
JLabel artikelID = new JLabel("Artikel nummer: ");
JButton voegReserveringToe = new JButton("Voeg toe");
voegReserveringToe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
voegReserveringToeActionPerformed(evt);
}
});
willekeurigPanel.add(dateBeginLabel);
willekeurigPanel.add(dateBeginField);
willekeurigPanel.add(dateEndLabel);
willekeurigPanel.add(dateEndField);
willekeurigPanel.add(klantID);
willekeurigPanel.add(klantnummer);
willekeurigPanel.add(artikelID);
willekeurigPanel.add(artikelnummer);
willekeurigPanel.add(voegReserveringToe);
container.add(willekeurigPanel);
container.add(overzichtPanel);
frame1.add(container);
frame1.setVisible(true);
}
As discussed here, don't set the size and position of components arbitrarily. Instead, let the layout do the work, nesting as required. Use the GroupLayout shown here for the labeled input fields. Add each to the CENTER of a panel having BorderLayout, with a button in the SOUTH on the left. Finally, add both panels to an enclosing panel having GridLayout(1, 0).
I am having a problem implementing the last part of this program, which is to make it where pressing the Enter key moves the active field from one text field to the next one in order (1,2,3,4).
This needs to be done without removing the focus cycling that is used by the tab key.
I have no idea how to even begin doing that, the only thing I've found in the API is replacing the traversal policy with your own, but I don't want to replace it I want to create a new one that runs in parallel with the default one.
public class unit27 {
JButton button1 = new JButton("add to next cup");
JButton button2 = new JButton("add to next cup");
JButton button3 = new JButton("add to next cup");
JButton button4 = new JButton("add to next cup");
JTextField text1 = new JTextField("4");
JTextField text2 = new JTextField("4");
JTextField text3 = new JTextField("4");
JTextField text4 = new JTextField("4");
JLabel label1 = new JLabel("Cup 1");
JLabel label2 = new JLabel("Cup 2");
JLabel label3 = new JLabel("Cup 3");
JLabel label4 = new JLabel("Cup 4");
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
public unit27() {
mainPanel.setLayout(new GridLayout(2, 4));
panel1.setLayout(new GridLayout(1, 3));
panel2.setLayout(new GridLayout(1, 3));
panel3.setLayout(new GridLayout(1, 3));
panel4.setLayout(new GridLayout(1, 3));
frame.add(mainPanel);
frame.setSize(800, 800);
frame.setVisible(true);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
mainPanel.add(panel4);
panel1.add(label1);
panel1.add(button1);
panel1.add(text1);
panel2.add(label2);
panel2.add(button2);
panel2.add(text2);
panel3.add(label3);
panel3.add(button3);
panel3.add(text3);
panel4.add(label4);
panel4.add(button4);
panel4.add(text4);
button1.add(text1);
button1.addActionListener(new MyListener1());
button2.addActionListener(new MyListener2());
button3.addActionListener(new MyListener3());
button4.addActionListener(new MyListener4());
// end class
}
class MyListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text1.getText());
int b = Integer.parseInt(text2.getText());
int c = a + b;
text2.setText(Integer.toString(c));
}
}
class MyListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text2.getText());
int b = Integer.parseInt(text3.getText());
int c = a + b;
text3.setText(Integer.toString(c));
}
}
class MyListener3 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text3.getText());
int b = Integer.parseInt(text4.getText());
int c = a + b;
text4.setText(Integer.toString(c));
}
}
class MyListener4 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text4.getText());
int b = Integer.parseInt(text1.getText());
int c = a + b;
text1.setText(Integer.toString(c));
}
}
public static void main(String[] args) {
new unit27();
}
}
Swing does not allow 2 focus cycles to be run at the same time. If you really need to have a second focus cycle (and not just add enter to the focus traversal keys), then what you could do is:
Create a Map which determines your cycle.
On each component with the extra cycle add a key binding for Enter that gets the next visible field in your cycle and calls requestFocus on it.
You would have to maintain the map and create custom checks to see if the next component is visible or should be skipped.
I'm having problem with adding another JPanel to my frame when I'm using combobox.
I want to change the center panel according to the selection in combobox.
I made differehnt panel to all selections but it didn't add to my main panel.
I added the code.
thanks :)
import AllClasses.FlightCompany;
{
public class WorkerDialog extends JFrame {
private JPanel Worker;
private String[] LabelNames = { "Worker Type:", " Worker Name:" };
String [] str = { "Office", "Host",
"Pilot" };
JComboBox<String> ChooseBox = new JComboBox<>(str);
public JPanel MainPanel;
private JPanel [] p= new JPanel[3];
public WorkerDialog(FlightCompany f) {
super("Worker Dialog");
p[0] = new Office_Gui();
p[1] = new Host_Gui();
p[2] = new Pilot_Gui();
Worker = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel LabelName = new JLabel(LabelNames[0]);
JLabel LabelName2 = new JLabel(LabelNames[1]);
JTextField fieldBox = new JTextField();
LabelName.setSize(40, 25);
ChooseBox.setPreferredSize(new Dimension(180, 22));
Worker.add(LabelName);
Worker.add(ChooseBox);
Worker.add(LabelName2);
fieldBox.setPreferredSize(new Dimension(180, 22));
Worker.add(fieldBox);
JPanel AddPanel = new JPanel(new GridLayout(2, 1, 1, 1));
AddPanel.add(new JButton("Add"));
AddPanel.add(new JButton("TakeOff"));
MainPanel = new JPanel(new BorderLayout(3, 3));
AddPanel.setPreferredSize(new Dimension(0, 110));
ChooseBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
//String str = e.getActionCommand();
String jb = (String) ChooseBox.getSelectedItem();
if (jb.equals("Office")){
MainPanel.add(p[0],BorderLayout.CENTER);
System.out.println("Office");}
}
});
MainPanel.add(Worker, BorderLayout.NORTH);
MainPanel.add(AddPanel, BorderLayout.SOUTH);
add(MainPanel);
//pack();
setSize(560, 300);
setAlwaysOnTop(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
What you want to do is use a CardLayout for your mainPanel, that will allow you to easily switch between panels. Then add all your panels to the mainPanel, specifying a name for the panel. That name will go in the combo box. When you want to show a certain panel, just call cardLayout.show(mainPanel, "nameOfPanel")
To learn more about Cardlayout see How to Use CardLayout. You can also see a simple example here
An aside: Use Java naming convention. Variables begin with lower case letters, using camel casing. ie:
ChooseBox → chooseBox
MainPanel → mainPanel
etc.
hello goodevening to all i have a problem on my program with the ScrollPane in my JList i cant put an JScrollPane in my list because i am using a panel instead of Container this is my code so far its all runnable the problem is if you enter a high number in the number of times the some output will not be able to see because of the size of my list . so this is the code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MultCen extends JFrame implements ActionListener
{
public static void main(String args [])
{
MultCen e = new MultCen();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.setSize(300,450);
}
JTextField t1 = new JTextField();
JTextField t2 = new JTextField();
JButton b = new JButton("Okay");
JButton c = new JButton("Clear");
JList list = new JList();
JLabel lab = new JLabel();
DefaultListModel m = new DefaultListModel();
public MultCen()
{
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel l = new JLabel("Enter a number :");
JLabel l1 = new JLabel("How many times :");
l.setBounds(10,10,130,30);
l1.setBounds(10,40,130,30);
t1.setBounds(140,10,130,25);
t2.setBounds(140,40,130,25);
b.setBounds(60,90,75,30);
c.setBounds(150,90,75,30);
list.setBounds(30,140,220,220);
panel.add(t1);
panel.add(t2);
panel.add(l);
panel.add(l1);
panel.add(list);
panel.add(b);
panel.add(c);
getContentPane().add(panel);
b.addActionListener(this);
c.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b)
{
int t3 = Integer.parseInt(t1.getText());
int t4 = Integer.parseInt(t2.getText());
m.addElement("The multiplication Table of "+t3);
for (int cc =1 ; cc <=t4; cc++ )
{
lab.setText(t3+"*"+cc+" = "+(t3*cc));
m.addElement(lab.getText());
list.setModel(m);
}
}
if(e.getSource() == c)
{
t1.setText("");
t2.setText("");
m.removeAllElements();
}
}
}
JScrollPane does not work with null Layout. Use BoxLayout or any other resizeable layout instead. This is the limitation of setLayout(null).
Use Layout managers. You've asked a lot of questions here and I'm sure a few you have been advised not to use null layout. Again here is the tutorial Laying out components Within a container. Learn to use them so you don't run into the million possible problems on the road ahead. This kind of problem being one of them.
here's an example of how you could achieve the same thing with layout managers, and some empty borders for white space.
With Layout Manager
Without Layout Manger
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class MultCen extends JFrame {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MultCen e = new MultCen();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.pack();
}
});
}
JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10);
JButton b = new JButton("Okay");
JButton c = new JButton("Clear");
JLabel lab = new JLabel();
DefaultListModel m = new DefaultListModel();
public MultCen() {
JPanel topPanel = new JPanel(new GridLayout(2, 2, 0, 5));
JLabel l = new JLabel("Enter a number :");
JLabel l1 = new JLabel("How many times :");
topPanel.add(l);
topPanel.add(t1);
topPanel.add(l1);
topPanel.add(t2);
JPanel buttonPanel = new JPanel();
buttonPanel.add(b);
buttonPanel.add(c);
buttonPanel.setBorder(new EmptyBorder(10, 0, 10, 0));
JList list = new JList();
JScrollPane scroll = new JScrollPane(list);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(new Dimension(300, 300));
JPanel panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(buttonPanel, BorderLayout.CENTER);
panel.add(scroll, BorderLayout.SOUTH);
panel.setBorder(new EmptyBorder(10, 15, 10, 15));
getContentPane().add(panel);
}
}
Side Notes
Run Swing apps from the Event Dispatch Thread. See Initial Threads
When you do decide to use layout managers, just pack() your frame instead of setSize()
Use better variable names.
See Extends JFrame vs. creating it inside the the program