Is there a way to create Table in Java AWT? - java

Is there way to create Table in Java AWT? I need to create simple Java AWT program for insert, edit, delete and read users from database.

Yes: Make your own table with a bunch of labels as cells, and a scroll pane. You can set it up to add more cells/labels on the fly, and add any features you want.
If you cannot or do not want to do the above, then you can seek out a third party library that creates tables for AWT.
Or take the much easier and faster option and just use swing.

you can make table in swing JTable. But now you should use Graphics:
import java.awt.*;
public class name extends Frame{
name(){
setLayout(new FlowLayout());
setSize(1000,1000);
setVisible(true);
}//end of name()
public void paint(Graphics g){//opening graphics
g.drawRect(10,50,100,100);//make a rectangle
g.drawRect(50,50,100,100);//another rectangle
g.drawRect(10,100,100,100);//and another
g.drawRect(50,100,100,100);//last rectangle
g.drawString("SOMTHING", 30,80);//write a text in a rectangle
}//end of graphics
public static void main(String[] args){
name n=new name();
}
}//end of Frame

You can create using a Panel with GridLayout, with the components (Labels or TextFields) and then you can place that panel inside your frame. Here is the example code! Hope this will work!
But the only problem is, we cannot set the size for the components which we placed in a GridLayout! Anyone knows how to set the size of the component in GridLayout, please leave a comment!
import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class AwtTable extends Frame{
AwtTable(){
Panel p = new Panel();
Color c = new Color(241, 216, 252);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","password");
PreparedStatement ps = con.prepareStatement("select * from table_name;");
ResultSet rs = ps.executeQuery();
TextField l1 =null,l2=null,l3=null,l4=null,l5=null,l6=null ;
int row=1;
while(rs.next()) {
l1 = new TextField();
l1.setText(rs.getString(1));
l2 = new TextField();
l2.setText(rs.getString(2));
l3 = new TextField();
l3.setText(Integer.toString(rs.getInt(3)));
l4 = new TextField();
l4.setText(rs.getString(4));
l5 = new TextField();
l5.setText(rs.getString(5));
l6 = new TextField();
l6.setText(Long.toString(rs.getLong(6)));
Button add = new Button("Edit");
Button delete = new Button("Delete");
add.setSize(70,20);
delete.setSize(70,20);
p.add(l1);p.add(l2);p.add(l3);p.add(l4);p.add(l5);p.add(l6);
p.add(add);p.add(delete);
p.setLayout(new GridLayout(row,8));
row++;
}
p.setBackground(Color.white);
p.setBounds(100,100,1000,400);
add(p);
setLayout(null);
setVisible(true);
setSize(700,500);
setTitle("Employee Datas");
setBackground(c);
}catch(Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
AwtTable at = new AwtTable();
}
}

Related

How to position Java swing components when there is a JScrollPane

I am new to making GUIs and Java Swing and I'm trying to make a GUI which displays a table from a SQL database. The table is displayed using a JScrollPane. At first I thought that my other components (JLabel and JTextField) weren't being added to the content pane but they actually were they were just hidden underneath the ScrollPane. After reducing the ScrollPane's dimensions, now these other components show up but they are unable to be positioned with the setBounds method and always appear in the same place so that the last component added covers up the other ones entirely. As well as the code I've also included a screenshot of what the GUI looks like.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class LibraryAppGUI extends JFrame {
String sql;
String DB_PATH = LibraryAppGUI.class.getResource("LibraryManagement3.sqlite").getFile();
private JTable table;
private String columns[] = {"PatronFirstName", "PatronLastName"};
private TableModelListener tableModelListener;
public LibraryAppGUI () {
DefaultTableModel model = new DefaultTableModel(columns, 0);
table = new JTable(model);
try{populateSQL(table);} catch(Exception e1) {e1.printStackTrace();}
table.setCellSelectionEnabled(true);
table.setPreferredScrollableViewportSize(new Dimension(600, 300));
table.setFillsViewportHeight(false);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVisible(true);
getContentPane().add(scrollPane, BorderLayout.PAGE_START);
}
public void createSQL() throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.jdbc");
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
PreparedStatement stmt = connection.prepareStatement("");
}
public void populateSQL(JTable table) throws ClassNotFoundException, SQLException {
sql = "select PatronFirstName, PatronLastName\r\n" +
"FROM Patron\r\n";
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet res = stmt.executeQuery();
while(res.next()) {
Object[] row = new Object[columns.length];
for (int i = 1; i <= columns.length; i++) {
row[i-1] = res.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(res.getRow()-1, row);
}
res.close();
connection.close();
}
public static void main(String[] args) {
LibraryAppGUI window = new LibraryAppGUI();
//label to prompt user
JLabel welcome = new JLabel("Welcome to the library. Choose your patron: ");
welcome.setBounds(50,50, 100, 30);
window.getContentPane().add(welcome);
JTextField user = new JTextField("Enter the full name in this box.");
user.setBounds(150,150,100,30);
window.getContentPane().add(user);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
Why do you create your Swing components in two different places?
Don't create components in the main() method.
The label, text field and table should all created and added to the frame in the constructor, the same way you create and add the scrollpane/table.
In your code below:
JLabel welcome = new JLabel("Welcome to the library. Choose your patron: ");
welcome.setBounds(50,50, 100, 30);
window.getContentPane().add(welcome);
JTextField user = new JTextField("Enter the full name in this box.");
user.setBounds(150,150,100,30);
window.getContentPane().add(user);
The setBounds(...) statements should NOT be used. By default the content pane of the frame uses a BorderLayout. The layout manager will set the size/location of the components based on the rules of the layout manager.
When you don't specify a constraint when you add the components, then the BorderLayout.CENTER is used. However you can only add one component to the CENTER, so only the text field is given the proper size/location. The label is ignored.
So, assuming you move the GUI code from the main() method to the constructor, the proper design would be to do something like:
JPanel top = new JPanel();
top.add(welcome);
top.add(user);
add(top, BorderLayot.PAGE_START);
then you would also use:
//getContentPane().add(scrollPane, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
This will now display the lable and text field at the top of the frame and the scrollpane in the center. The scrollbars will then automatically adjust as the frame size is changed.

Editable JComboBox gives error: <identifier> expected and illegal start of type

I am trying to create and Editable JComboBox to allow the user to type the name of the song to purchase. However when I set tunes.setEditable(true); I get an error... any help will be appreciated!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
Thank you!
Actually, Java requires that you setup JComponents in the constructor. In order for your code to work, you need to call on setEditable(true) in the constructor, which means that you just need to move tunes.setEditable(true); to the constructor.
Tip: always allocate memory for JComponents in the constructor (you want to draw the components as soon as you create the Jframe). You can have a reference to the JComboBox at the class level.
Here is another version of your code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes;
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes2 frame = new JTunes2();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
You added the tunes.setEditable(true) at the class level, instead of at the method level. No statements allowed at the class level!
Here's a fixed version: I renamed JTunes2 to JTunes to fix the compilation errors, and moved the setEditable to the constructor. Also I fixed the indentation - this makes it harder to make this mistake:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}

JLabel does not appear in the JFrame

I am having trouble implementing JLabel with JFrame. The program needs to show either "Hello" or "World" in the center of the screen when the button "study" is pressed. Also with this being a flashcard program, when study is pressed a word is placed on the middle of the screen and the program is suppose to read from the text field for the user input and print whether it is right or wrong. The problem is that the program is reading the text field after study is pressed so it is printing false before the user can input a answer.
Can someone briefly explain why this is not working and what I can do to fix this issue?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class NoteCardGUI implements ActionListener {
public static JFrame frame;
public static JPanel panel;
public static JLabel label;
private NoteCard ex;
private JButton study;
public static Box box1 = new Box(), box2 = new Box(), box3 = new Box();
public NoteCardGUI() {
ex = new NoteCard("Hello", "World");
frame = new JFrame("Flash Card");
panel = new JPanel();
study = new JButton("Study");
study.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String resp = NoteCard.getResponse(ex);
String chal = NoteCard.getChallenge(ex);
String a = text.getText();
label = new JLabel(chal, label.CENTER);
label.setAlignmentX(0);
label.setAlignmentY(0);
frame.add(label, BorderLayout.SOUTH);
frame.revalidate();
if(resp.compareTo(a) == 0)
{
label = new JLabel("Correct!");
}
label = new JLabel("Incorrect");
}
});
panel.add(study);
frame.add(panel);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new NoteCardGUI();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
You are adding the label to your frame, but you already have added a JPanel on top of the frame. The solution is to add the label to the panel instead of the frame.
So change: frame.add(label); to panel.add(label);
By default, a JFrame (or rather, its content pane) has BorderLayout. This means that if you add components to it without specifying a constraint, they will be added at the CENTER. But you can't add more than one element at any of the BorderLayout's regions.
So in order for this to work, you need to add the label somewhere else other than the center, or have the panel added with some other, explicit region.
So if you change the add, for example, to:
frame.add(label, BorderLayout.NORTH);
It will work - but you must not forget to also add:
frame.revalidate();
Whenever you add components to your GUI, you should call this when you've added them all, in order for it to rebuild the hierarchy of components as needed.
Another option would be to change the layout manager of the Frame, or to add to the panel.

refill JTable from

I open JDialog from main window to show set of data, retrieved according to parameters and mode.
(in this simplified version parameters doesn't matter, just "Mode", in real I fill it from recordset).I want
1.to fill table in Dialog Window initially
optionally use button to show another set of data, retrieved with different mode
First mission is OK. Creating table and filling is organised as procedure
that works properly from dialog constructor.
But when I run this procedure from ActionListener of button -- I get another copy of table in the same window - it makes sense because I create it once again as "new". I cant find the way I can refill data on the same table! All examples on the net are about creating a new one
Here is calling part
btnFreqHistory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Running history");
DlgFreqHistory FreqHist= new DlgFreqHistory(1000,2,1 );
FreqHist.setDefaultCloseOperation(FreqHist.DISPOSE_ON_CLOSE);
FreqHist.setVisible(true);
}
});
Here is JDialog part:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import java.sql.ResultSet;
public class DlgFreqHistory extends JDialog {
private final JPanel contentPanel = new JPanel();
static int Freq;
static int Side;
static int Mode; //1- last 10 results, 2 - best results
/**
* Launch the application.
*/
public static void main(String[] args) {
}
/**
* Create the dialog.
*/
public DlgFreqHistory(int iFreq, int iSide, int iMode) {
Freq = iFreq;
Side = iSide;
Mode = iMode;
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
this.setTitle("Last results for " + iFreq );
**// !! This call works fine**
GetHistoryByMode(iFreq, iSide, 2);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
JButton btn_getData = new JButton("Get data");
btn_getData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println("in action performed");
***// !! This call creates another table***
GetHistoryByMode(Freq, Side, 1);
}
} );
buttonPane.add(btn_getData);
getRootPane().setDefaultButton(btn_getData);
}
private void GetHistoryByMode(int Freq, int iSide, int Mode)
{
System.out.println("in GetHistoryByMode " + Freq + " " + iSide + " " + Mode);
String HistColumns[] = new String[2];
String HistData[][] = new String[10][2];
if (Mode==1) {
HistColumns[0] = "X1";
HistColumns[1] = "Result";
HistData[0][0] = "xx1";
HistData[0][1] = "15";
HistData[1][0] = "xx2";
HistData[1][1] = "20";
}
if (Mode==2) {
HistColumns[0] = "Y1";
HistColumns[1] = "Result";
HistData[0][0] = "yy1";
HistData[0][1] = "15";
HistData[1][0] = "yy2";
HistData[1][1] = "23";
}
JTable FreqHistory = new JTable(HistData, HistColumns);
contentPanel.add(FreqHistory);
JScrollPane scrollPane;
scrollPane = new JScrollPane( FreqHistory );
contentPanel.add( scrollPane, BorderLayout.CENTER );
}
}
Don't create the JTable in the GetHistoryByMode method, instead, create it within the constructor and add it to the UI there. Then in the GetHistoryByMode method, create a new TableModel and apply it (setModel) to the existing JTable
Take a look at How to Use Tables for more details
You might also like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Replacing a JPanel with a different JPanel

Hi this is a bit of a basic question. In my code I create a gui in a constructor then nest a ActionListener class to handle button changes. This code will create the gui and the action listener runs through the actionPerformed method correctly. However, I've tried multiple ways to change the panel in the gui but I feel like the way I have the program set up it is not possible for this to work. Sorry if this is a repeat but after searching for a while on S.O. I haven't found a good example that would help me with my problem.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import org.math.plot.Plot2DPanel;
import org.math.plot.plotObjects.BaseLabel;
public class GraphGui extends JFrame {
//default width and height of the GUI
private static final int WIDTH = 1200;
private static final int HEIGHT = 700;
GraphPlot gp = new GraphPlot();
Plot2DPanel plotPanel =gp.determinePlotToPlot("duration");
/**
* This is the constructor that initializes the JFrame and the layout of the GUI.
* The radio buttons are also created here and grouped accordingly.
*/
public GraphGui() {
//title of GUI
setTitle("VibeTech Graph Gui");
//First JRadioButton for date vs duration
JRadioButton durToDate = new JRadioButton("Duration vs. Date");
durToDate.addActionListener(new RadioButtonListener());
durToDate.setActionCommand("duration");
durToDate.setSelected(true);
//JRadioButton for weight vs date
JRadioButton weightToDate = new JRadioButton("Weight vs. Date");
weightToDate.addActionListener(new RadioButtonListener());
weightToDate.setActionCommand("weight");
//JRadioButton for plan type vs date
JRadioButton planToDate = new JRadioButton("Plan vs. Date");
planToDate.addActionListener(new RadioButtonListener());
planToDate.setActionCommand("level");
//button group of the buttons to display them as one group
ButtonGroup group = new ButtonGroup();
group.add(planToDate);
group.add(weightToDate);
group.add(durToDate);
//create JPanel to add objects to
JPanel jplRadio = new JPanel();
jplRadio.setLayout(new GridLayout(0, 1));
//add radio buttons
jplRadio.add(planToDate);
jplRadio.add(weightToDate);
jplRadio.add(durToDate);
Plot2DPanel dvt = new Plot2DPanel();
dvt.addLinePlot("Duration over Time", gp.getDate(), gp.getDuration());
BaseLabel title = new BaseLabel("Duration over Time", Color.RED,
0.5, 1.1);
title.setFont(new Font("Courier", Font.BOLD, 20));
dvt.addPlotable(title);
dvt.setAxisLabels("Time", "Duration");
setLayout(new BorderLayout());
add(jplRadio, BorderLayout.WEST);
add(plotPanel, BorderLayout.EAST);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//main method to run program
public static void main(String [ ] args)
{
//create new GUI
#SuppressWarnings("unused")
GraphGui test = new GraphGui();
}
//create a radio button listener to switch graphs on button press
class RadioButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("duration")) {
plotPanel = gp.determinePlotToPlot("duration");
} else if (e.getActionCommand().equals("weight")) {
plotPanel = gp.determinePlotToPlot("weight");
} else if (e.getActionCommand().equals("level")) {
plotPanel = gp.determinePlotToPlot("level");
}
//here is where I tried to do removes, adds, and validates but
//I have trouble getting to the frame itself to remove the JPanel
//component. I think this is a setup problem.
}
}
}
You would need to add the panel and revalidate/repaint the JFrame for it to appear:
add(plotPanel, BorderLayout.EAST);
revalidate();
repaint();
Better to use CardLayout to manage this type of functionality.
Try using CardLayout for switching between panels. Here is my solution for a similar question: https://stackoverflow.com/a/9377623/544983

Categories

Resources