I have made a little minimum example.
I have a jTabbedPane with two tabs.
After pressing a button in TabPanel2 a table shut showing up.
But the table does not appear.
Please help me. Thank you.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
public class test extends JFrame {
private JButton jButton1 = new JButton();
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private JPanel jTabbedPane1TabPanel1 = new JPanel(null, true);
private JPanel jTabbedPane1TabPanel2 = new JPanel(null, true);
private JButton jButton2 = new JButton();
public void jButton2_ActionPerformed(ActionEvent evt) {
DefaultTableModel tableModel = new DefaultTableModel(0,2);
tableModel.addRow(new Object[] {"string1","string2"});
JTable table1 = new JTable(tableModel);
jTabbedPane1TabPanel2.add(table1);
}
}
`public class test extends JFrame implements ActionListener {
private JButton jButton1 = new JButton("button1");
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private JPanel jTabbedPane1TabPanel1 = new JPanel();
private JPanel jTabbedPane1TabPanel2 = new JPanel();
private JButton jButton2 = new JButton("button2");
public test() {
jTabbedPane1TabPanel1.add(jButton1);
jTabbedPane1TabPanel2.add(jButton2, BorderLayout.PAGE_START);
jTabbedPane1.addTab("1", jTabbedPane1TabPanel1);
jTabbedPane1.addTab("2", jTabbedPane1TabPanel2);
jButton2.addActionListener(this);
JFrame frame = new JFrame();
frame.setContentPane(jTabbedPane1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
DefaultTableModel tableModel = new DefaultTableModel(0, 2);
tableModel.addRow(new Object[] {
"string1", "string2"
});
JTable table1 = new JTable(tableModel);
// System.out.println(table1.getColumnCount());
// System.out.println(table1.getRowCount());
jTabbedPane1TabPanel2.add(table1, BorderLayout.CENTER);
}
public static void main(String[] args) {
new test();
}
}`
Related
I need to insert the window with the tabbed called "First panel, Second panel, Third panel, Fourth panel" into the window named "Animation".
What should I do so that at the end it looks like: a window that has an animation box with four tabs, a Text box and a User input box?
First class called "Main" :
import java.awt.*;
import javax.swing.*;
public class Main {
JFrame frame = new JFrame("Demo");
JPanel panel = new JPanel();
JLabel square1 = new JLabel("Animation");
JLabel square2 = new JLabel("Text");
JTextField square3 = new JTextField("User Input");
public Main() {
panel.setLayout(new GridLayout(2,2,3,3));
panel.add(square1);
panel.add(square2);
panel.add(square3);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(600,400);
frame.setVisible(true);
}
public static void main(String[] args) {
Tabbed tp = new Tabbed();
tp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
tp.setSize(600,400);
tp.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
}
});
}
}
'Second class called "Tabbed" :'
import javax.swing.*;
public class Tabbed extends JFrame{
private static final long serialVersionUID = 1L;
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
JPanel thirdPanel = new JPanel();
JPanel fourPanel = new JPanel();
JLabel firstLabel = new JLabel("First!");
JLabel secondLabel = new JLabel("Second!");
JLabel thirdLabel = new JLabel("Third!");
JLabel fourLabel = new JLabel("Fourth!");
JTabbedPane tabbedPane = new JTabbedPane();
public Tabbed(){
firstPanel.add(firstLabel);
secondPanel.add(secondLabel);
thirdPanel.add(thirdLabel);
fourPanel.add(fourLabel);
tabbedPane.add("First panel",firstPanel);
tabbedPane.add("Second panel",secondPanel);
tabbedPane.add("Third panel",thirdPanel);
tabbedPane.add("Fourth panel",fourPanel);
add(tabbedPane);
}
}
Here's how I want to combine the two windows :
I keep receiving this error
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;
import java.awt.Container.*;
public class main extends JFrame implements ActionListener
{
JButton CustomerOrder;
JButton SoftwareProducts;
JButton BooksProducts;
JButton AddBooks;
JButton StaffMember;
JButton LoginView;
static ArrayList<Software> softwareList = new ArrayList<Software>();
CardLayout c1 = new CardLayout();
JPanel mainPanel;
SoftwareProducts addsoftware;
CustomerOrder customerorder;
BooksProducts addProduct;
AddBooks addBook;
SoftwareProducts sf = new SoftwareProducts();
//Press submit;
public static void main(String[] args)
{
new main();
JFrame frame = new JFrame("Selling Product");
frame.setLocationRelativeTo(null);
//frame.getContentPane().add(main, BorderLayout.CENTER);
//new CustomerOrder();
//EmailFrame email=new EmailFrame();
//CustomerOrder co = new CustomerOrder();
//LoginView login = new LoginView();
}
public main(){
super();
// getContentPane().setBackground(Color.green);
setSize(700,800);
setLayout(new FlowLayout());
/*CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "softwareProducts");
*/
//CustomerOrder co = new CustomerOrder();
//add(co);
SoftwareProducts = new JButton("SoftwareProducts");
SoftwareProducts.setSize(150,40);
SoftwareProducts.setLocation(20,50);
CustomerOrder = new JButton("CustomerOrder");
CustomerOrder.setSize(160,40);
CustomerOrder.setLocation(150,50);
BooksProducts = new JButton("BooksProducts");
BooksProducts.setSize(200,40);
BooksProducts.setLocation(310,50);
AddBooks = new JButton("AddBook");
AddBooks.setSize(200,40);
AddBooks.setLocation(310,50);
StaffMember = new JButton("StaffMember");
StaffMember.setSize(200,40);
StaffMember.setLocation(310,50);
LoginView = new JButton("LoginView");
LoginView.setSize(150,40);
LoginView.setLocation(20,50);
SoftwareProducts.addActionListener(this);
add(SoftwareProducts);
CustomerOrder.addActionListener(this);
add(CustomerOrder);
BooksProducts.addActionListener(this);
add(BooksProducts);
AddBooks.addActionListener(this);
add(AddBooks);
StaffMember.addActionListener(this);
add(StaffMember);
mainPanel = new JPanel();
mainPanel.setBackground(Color.BLUE);
mainPanel.setPreferredSize(new Dimension(600,500));
mainPanel.setLayout(c1);
addsoftware = new SoftwareProducts();
mainPanel.add(addsoftware,"addsoftware");
customerorder = new CustomerOrder(); ////// I am getting the error
from this part of code
mainPanel.add(customerorder,"customerorder");///// I am getting the
error from this part of code
addProduct = new BooksProducts();
mainPanel.add(addProduct,"addProduct");
addBook = new AddBooks();
mainPanel.add(addBook,"addBook");
/* mainPanel.add(SoftwareProducts);
mainPanel = new JPanel(new CardLayout());
mainPanel.add(SoftwareProducts);
getContentPane().add(mainPanel);
addProduct = new BooksProducts();
mainPanel.add(addProduct,"addProduct");
*/
add(mainPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == SoftwareProducts)
{
c1.show(mainPanel,"addsoftware");
this.setTitle("SoftwareProducts");
//System.out.println("Softwares");
}
if(e.getSource() == CustomerOrder)
{
c1.show(mainPanel,"customerorder");
this.setTitle("CustomerOrder");
//System.out.println("Custmers");
}
if(e.getSource() == BooksProducts)
{
c1.show(mainPanel,"addProduct");
this.setTitle("BooksProducts");
}
if(e.getSource() == AddBooks)
{
c1.show(mainPanel,"addBook");
this.setTitle("AddBooks");
}
if(e.getSource() == LoginView)
{
c1.show(mainPanel,"LogIN");
this.setTitle("LOGIN");
}
}
/* public void actionPerformed(ActionEvent e)
{
if(e.getSource() == press)
{
System.out.println("addProducts");
}
}*/
}
and my customerOrder class
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.*;
import java.io.*;
public class CustomerOrder extends JFrame
implements ActionListener
{
//JButton asd = new JButton("BUTTON");
//JTextField productID;
//JTextField productName;
//JTextField productCost;
//JTextField productPYear;
//JTextField productPHouse;
JButton showOrder;
DefaultListModel<String> model = new DefaultListModel<>();
JList <String>orderList = new JList(model);
JTable softwareTabel = new JTable();
//DefaultTableModel tableModel = new DefaultTableModel(0, 1);
public CustomerOrder()
{
//super();
// JLabel toLabel=new JLabel("Product ID: ");
//JTextField to=new JTextField();
setLayout(new FlowLayout());
/*
productName = new JTextField(12);
add(productName);
productCost = new JTextField(12);
add(productCost);
productPYear = new JTextField(12);
add(productPYear);
productPHouse = new JTextField(12);
add(productPHouse);
*/
showOrder = new JButton("SHOW ORDER");
showOrder.setSize(25,40);
showOrder.addActionListener(this);
add(showOrder);
}
public void actionPerformed(ActionEvent e)
{
//Object[] colNames={"Product ID","Processor","RAm"};
if(e.getSource() == showOrder)
{
model.removeAllElements();
/* GridLayout exLayout = new GridLayout(3, 3);
JLabel ram,processor;
ram = new JLabel("RAM");
processor = new JLabel("Processor");
String softwaredata[] = {"ID","RAM","Processor","Product ID","Product Name","Product Year","Product Year","Product PublishHouse"};
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 3));
add(ram);
add(processor);
JTable table = new JTable();*/
//DeafultTableModel dm = new DeafultTableModel(0,0);
//String header[] = new String[] {"RAM", "Processor","ProductID","Product Name","Product Year","Product Publish House"};
//dm.setColumnIdentifiers(header);
//Object[][] software = new Object[8][3];
//model.addRow(orderList.toArray());
int x = 0;
while (x < main.softwareList.size())
{
//./model.addElement(main.softwareList.get(x).getproductYear());
model.addElement(""+main.softwareList.get(x).getproductID());
model.addElement(""+main.softwareList.get(x).getRam());
model.addElement(""+ main.softwareList.get(x).getProcessor());
model.addElement(""+ main.softwareList.get(x).getproductID());
model.addElement(main.softwareList.get(x).getproductName());
model.addElement(""+ main.softwareList.get(x).getproductYear());
model.addElement(main.softwareList.get(x).getproductPublishHouse());
//model.addElement(main.softwareList.get(x).getproductID());*/
x++;
//System.out.println("as");
}
/* ArrayList<String> table1 = new ArrayList();
ArrayList<ArrayList<String>> table2 = new ArrayList();
table1.add("Product ID");
table1.add("RAM");
table1.add("Processor");
table1.add("Product Name");
table1.add("Product Year");
table1.add("Product PHouse");
Object[] software = table1.toArray();
String[] [] softwarest = new String[table1.size()][];
int i = 0;
for (List<String> next : table2){
softwarest[i++] = next.toArray(new String[next.size()]);
}
JTable newTable = new JTable(softwarest,software);
JFrame frame = new JFrame();
frame.getContentPane().add(new JScrollPane(newTable));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
*/
//table.add(model);
// add(orderList);
//Object[] column = {"RAM:", "Processor:"};
//Object[][] data = {{"RAM:", "Processor:"}};
//JTable table = new JTable();
//table.setShowGrid(false);
//table.setTableHeader(null);
}
}
}
When i run this code i get the following exception from the main class in customerorder = new CustomerOrder;
mainPanel.add(customerorder,"customerorder")
customorder is an instance of CustomerOrder, which extends from JFrame; public class CustomerOrder extends JFrame
As the error states illegalargumentexception adding a window to a container; it is illegal to add a window to another window, it simply doesn't make sense.
This is one of the reasons we discourage extending from top level containers like JFrame directly.
Either make the CustomerOrder visible like any normal frame (although that might lead you into other issues) or better yet, base your CustomerOrder component of a JPanel
public class CustomerOrder extends JPanel {
//...
}
This way you can add it to what ever container you need to.
Idk if this logic is correct, but in just playing around to try and figure out the reason it doesn't make sense for myself I concluded that:
extending JFrame causes only one object to be created and why it tries to add the JFrame frame; object to itself which causes the exception...
extending JPanel allows the JFrame frame; <-- object to divide into a Container & a Component which allows you to
frame.add(this) ..
frame.add(this) is the component invoked by JPanel method .add()
if this is wrong plz correct..
I tried fixing this in so many ways, and tried searching for answers everywhere, my color buttons are working, but same way built number buttons do not....
package tralala;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class DugmiciKojiMenjajuBoju extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 4317497849622426733L;
private JButton dugme1;
private JButton dugme2;
private JButton dugme3;
private JPanel panel;
private JOptionPane a;
private JPanel panel1;
private JButton dugmeBroja0;
private JButton dugmeBroja1;
private JButton dugmeBroja2;
private JButton dugmeBroja3;
private JButton dugmeBroja4;
private JButton dugmeBroja5;
private JButton dugmeBroja6;
private JButton dugmeBroja7;
private JButton dugmeBroja8;
private JButton dugmeBroja9;
private JButton dugmeZaPlus;
private JButton dugmeZaMinus;
private JButton dugmeZaPuta;
private JButton dugmeZaPodeljeno;
private JButton dugmeZaJednako;
private JTextField polje;
DugmiciKojiMenjajuBoju(){
getContentPane().setBackground(Color.white);
this.setLayout(new FlowLayout());
a = new JOptionPane("");
dugme1 = new JButton("zuta");
dugme2 = new JButton("plava");
dugme3 = new JButton("crvena");
dugmeBroja0 = new JButton("0");
dugmeBroja1 = new JButton("1");
dugmeBroja2 = new JButton("2");
dugmeBroja3 = new JButton("3");
dugmeBroja4 = new JButton("4");
dugmeBroja5 = new JButton("5");
dugmeBroja6 = new JButton("6");
dugmeBroja7 = new JButton("7");
dugmeBroja8 = new JButton("8");
dugmeBroja9 = new JButton("9");
dugmeZaPlus = new JButton("+");
dugmeZaMinus = new JButton("-");
dugmeZaPuta = new JButton("*");
dugmeZaPodeljeno = new JButton("/");
dugmeZaJednako = new JButton("=");
polje = new JTextField("", 20);
panel = new JPanel();
panel1 = new JPanel();
dugmeBroja0.setSize(50,50);
dugmeBroja1.setSize(50,50);
dugmeBroja2.setSize(50,50);
dugmeBroja3.setSize(50,50);
dugmeBroja4.setSize(50,50);
dugmeBroja5.setSize(50,50);
dugmeBroja6.setSize(50,50);
dugmeBroja7.setSize(50,50);
dugmeBroja8.setSize(50,50);
dugmeBroja9.setSize(50,50);
panel1.add(dugmeBroja0);
panel1.add(dugmeBroja1);
panel1.add(dugmeBroja2);
panel1.add(dugmeBroja3);
panel1.add(dugmeBroja4);
panel1.add(dugmeBroja5);
panel1.add(dugmeBroja6);
panel1.add(dugmeBroja7);
panel1.add(dugmeBroja8);
panel1.add(dugmeBroja9);
panel1.add(dugmeZaPlus);
panel1.add(dugmeZaMinus);
panel1.add(dugmeZaPuta);
panel1.add(dugmeZaPodeljeno);
panel1.add(dugmeZaJednako);
panel1.add(polje);
panel1.setLayout(new FlowLayout(50, 0 ,0));
FlowLayout mojLayout = new FlowLayout(FlowLayout.CENTER , 20 , 20);
panel.setLayout(mojLayout);
panel.add(dugme1);
panel.add(dugme2);
panel.add(dugme3);
this.setTitle("Kalkulator Koji Menja Boju Pozadine");
this.setSize(500,500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.add(panel1);
this.add(panel);
dugme1.addActionListener(this);
dugme2.addActionListener(this);
dugme3.addActionListener(this);
polje.addActionListener(this);
panel.setBackground(Color.white);
panel1.setBackground(Color.white);
}
public static void main(String[] args) {
DugmiciKojiMenjajuBoju a = new DugmiciKojiMenjajuBoju();
a.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if( arg0.getSource() == dugme1){
panel.setBackground(Color.yellow);
panel1.setBackground(Color.yellow);
getContentPane().setBackground(Color.yellow);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D" ,"Postavili ste zutu",JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugme2){
panel.setBackground(Color.blue);
panel1.setBackground(Color.blue);
getContentPane().setBackground(Color.blue);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D","Postavili ste plavu", JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugme3){
panel.setBackground(Color.red);
panel1.setBackground(Color.red);
getContentPane().setBackground(Color.red);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D","Postavili ste crvenu",JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugmeBroja0){
polje.setText("0");
System.out.println("blabla");
}
}
}
My button 0 is not working... so i cannot continue writing the code.
My button 0 is not working... so i cannot continue writing the code.
You didn't add an ActionListener to the button.
However, before just fixing that problem you should simplify your code an learn how to use loops to create multiple components with the same functionality. Here is an example that creates a single ActionListener and add it to each button:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Also, don't use setSize() on your components. The layout manager is responsible for determining the size of a component.
You have never added ActionListener to that button, just to three color buttons and a JTextField polje
I think you didn't added this as the actionListener of dugmeBroja0:
you need this:
dugmeBroja0.addActionListener(this);
I know that this kind of issue has been discussed here many times, but I'm confused. I'm totally beginner in Java and I honestly don't know what to do and I admit that I don't have that much time to read whole documentation provided by Oracle. Here's my problem:
I'm trying to program a GUI for my program that will be show interference of acoustic waves. Mathematical functionality doesn't matter in here. I've got two classes called Window and Sliders. Window is intended to be a 'main GUI class' and Sliders is supposed to inherit (?) from it.
This comes from another issue that I need to implement ActionListener in class Window and ChangeListener in Sliders class. I heard that one class can't implement several classes that's why I made two.
Now, I wrote a little bit chaotic those two classes, but I don't know how to combine them. It's really silly, but after C++ I'm pretty confused how to tell the program that it is supposed to show in one frame either buttons defined in Window class and sliders defined in Sliders class. Currently it shows only buttons I want to make it showing sliders too.
I'm very sorry for chaotic pseudo code, please help. Please, try to explain as simply as you can/possible. Please feel free to ignore overrided methods, they're not finished yet.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class Window extends JFrame implements ActionListener
{
private JButton showChord, playSound, getSample, getPlot;
private JLabel chordInfo;
private JPanel basicFunctions;
public Window()
{
init();
}
private void init()
{
setVisible(true);
setSize(new Dimension(1000,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
basicFunctions = new JPanel();
FlowLayout basicLayout = new FlowLayout();
basicFunctions.setLayout(basicLayout);
showChord = new JButton("Akord");
playSound = new JButton("Odtwórz");
getSample = new JButton("Pobierz dźwięk");
getPlot = new JButton("Pobierz wykres");
showChord.addActionListener(this);
playSound.addActionListener(this);
getSample.addActionListener(this);
getPlot.addActionListener(this);
basicFunctions.add(showChord);
basicFunctions.add(playSound);
basicFunctions.add(getSample);
basicFunctions.add(getPlot);
add(basicFunctions);
Sliders param = new Sliders();
}
public static void main(String[] args)
{
Window frame = new Window();
}
//Action Listener
#Override
public void actionPerformed(ActionEvent a)
{
Object event = a.getSource();
if(event == showChord)
{
}
else if(event == playSound)
{
}
else if(event == getSample)
{
}
else if(event == getPlot)
{
}
}
}
import java.awt.*;
import javax.swing.event.ChangeEvent;
import javax.swing.*;
import javax.swing.event.ChangeListener;
public class Sliders extends Window implements ChangeListener
{
private JPanel sliders, sliderSub;
private JTextField accAmplitude, accFrequency, accPhase;
private JSlider amplitude, frequency, phase;
private double amplitudeValue, frequencyValue, phaseValue;
public Sliders()
{
sliders = new JPanel();
sliders.setLayout(new FlowLayout());
amplitude = new JSlider(0,100,0);
amplitude.setMajorTickSpacing(10);
amplitude.setMinorTickSpacing(5);
amplitude.setPaintTicks(true);
amplitude.setPaintLabels(true);
frequency = new JSlider(0,10,0);
frequency.setMajorTickSpacing(1);
frequency.setMinorTickSpacing(1/10);
frequency.setPaintTicks(true);
frequency.setPaintLabels(true);
phase = new JSlider(0,1,0);
phase.setMinorTickSpacing(2/10);
phase.setPaintTicks(true);
phase.setPaintLabels(true);
accAmplitude = new JTextField();
accFrequency = new JTextField();
accPhase = new JTextField();
sliders.add(amplitude, BorderLayout.NORTH);
sliders.add(frequency, BorderLayout.CENTER);
sliders.add(phase, BorderLayout.SOUTH);
add(sliders);
}
#Override
public void stateChanged(ChangeEvent arg0)
{
}
}
I've done this so far, but those text fields just stopped showing sliders values and I don't know why. They are defined in the Parameters class and Window class. Can someone help? Additionally in the future I'd like to make those text fields editable so that you can set slider value by typing it in the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.event.*;
public class Window extends JPanel
{
private JMenuBar mainMenu = new JMenuBar();
private Plot plot = new Plot();
private Parameters param = new Parameters();
private JComboBox chooseChord = new JComboBox();
private JButton playSound = new JButton("Odtwórz");
private JButton getSample = new JButton("Pobierz dźwięk");
private JButton getPlot = new JButton("Pobierz wykres");
private JPanel mainPanel = new JPanel();
private JPanel subPanel = new JPanel();
private JPanel buttonsPanel = new JPanel();
private JPanel slidersPanel = new JPanel();
private JLabel chord = new JLabel("Akord:");
private JTextField aValue = new JTextField();
private JTextField fValue = new JTextField();
private JTextField pValue = new JTextField();
public Window()
{
mainPanel.setLayout(new FlowLayout());
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS));
slidersPanel.setLayout(new BorderLayout());
subPanel.setLayout(new BorderLayout());
chooseChord.addItem("A");
chooseChord.addItem("A#");
chooseChord.addItem("Ab");
chooseChord.addItem("B");
chooseChord.addItem("Bb");
chooseChord.addItem("C");
chooseChord.addItem("C#");
chooseChord.addItem("Cb");
chooseChord.addItem("D");
chooseChord.addItem("D#");
chooseChord.addItem("E");
chooseChord.addItem("F");
chooseChord.addItem("F#");
buttonsPanel.add(chord);
buttonsPanel.add(chooseChord);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(playSound);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(getSample);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(getPlot);
buttonsPanel.setBorder(BorderFactory.createTitledBorder("Menu"));
slidersPanel.add(param);
JMenu langMenu = new JMenu("Język");
mainMenu.add(langMenu);
subPanel.add(buttonsPanel, BorderLayout.NORTH);
subPanel.add(slidersPanel, BorderLayout.SOUTH);
mainPanel.add(subPanel);
mainPanel.add(plot);
add(mainPanel);
param.addAmplitudeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent a)
{
double ampValue = param.getAmplitudeValue();
aValue.setText(String.valueOf(ampValue));
}
}
);
param.addFrequencyListener(new ChangeListener()
{
public void stateChanged(ChangeEvent f)
{
double frValue = param.getFrequencyValue();
fValue.setText(String.valueOf(frValue));
}
}
);
param.addPhaseListener(new ChangeListener()
{
public void stateChanged(ChangeEvent p)
{
double phValue = param.getPhaseValue();
pValue.setText(String.valueOf(phValue));
}
}
);
}
public JMenuBar getmainMenu()
{
return mainMenu;
}
private static void GUI()
{
Window mainPanel = new Window();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setJMenuBar(mainPanel.getmainMenu());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
GUI();
}
}
);
}
}
class Parameters extends JPanel
{
private JPanel pane = new JPanel();
private JPanel ampPanel = new JPanel();
private JPanel frPanel = new JPanel();
private JPanel phPanel = new JPanel();
private JSlider amplitude = new JSlider(0,100,0);
private JSlider frequency = new JSlider(0,10000,0);
private JSlider phase = new JSlider(0,180,0);
private JLabel pLabel = new JLabel("Faza");
private JLabel aLabel = new JLabel("Amplituda (dB)");
private JLabel fLabel = new JLabel("Częstotliwość (Hz)");
private JTextField preciseAmplitude = new JTextField(3);
private JTextField preciseFrequency = new JTextField(4);
private JTextField precisePhase = new JTextField(3);
public Parameters()
{
preciseAmplitude.setEditable(true);
preciseFrequency.setEditable(true);
precisePhase.setEditable(true);
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
ampPanel.setLayout(new FlowLayout());
frPanel.setLayout(new FlowLayout());
phPanel.setLayout(new FlowLayout());
amplitude.setMajorTickSpacing(10);
amplitude.setMinorTickSpacing(5);
amplitude.setPaintTicks(true);
amplitude.setPaintLabels(true);
frequency.setMajorTickSpacing(2000);
frequency.setMinorTickSpacing(100);
frequency.setPaintTicks(true);
frequency.setPaintLabels(true);
phase.setMajorTickSpacing(2/10);
phase.setPaintTicks(true);
phase.setPaintLabels(true);
setBorder(BorderFactory.createTitledBorder("Parametry fali"));
ampPanel.add(aLabel);
ampPanel.add(preciseAmplitude);
pane.add(ampPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(amplitude);
pane.add(Box.createRigidArea(new Dimension(0,10)));
frPanel.add(fLabel);
frPanel.add(preciseFrequency);
pane.add(frPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(frequency);
pane.add(Box.createRigidArea(new Dimension(0,10)));
phPanel.add(pLabel);
phPanel.add(precisePhase);
pane.add(phPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(phase);
pane.add(Box.createRigidArea(new Dimension(0,10)));
add(pane);
}
public int getAmplitudeValue()
{
return amplitude.getValue();
}
public int getFrequencyValue()
{
return frequency.getValue();
}
public int getPhaseValue()
{
return phase.getValue();
}
public void addAmplitudeListener(ChangeListener ampListener)
{
amplitude.addChangeListener(ampListener);
}
public void addFrequencyListener(ChangeListener frListener)
{
frequency.addChangeListener(frListener);
}
public void addPhaseListener(ChangeListener phListener)
{
phase.addChangeListener(phListener);
}
}
class Plot extends JPanel
{
private JPanel componentWave = new JPanel();
private JPanel netWave = new JPanel();
private JLabel componentLabel = new JLabel("Fale składowe");
private JLabel netLabel = new JLabel("Fala wypadkowa");
private JLabel wave = new JLabel("Wybierz falę składową");
private JPanel labels = new JPanel();
private JComboBox chooseWave = new JComboBox();
public Plot()
{
labels.setLayout(new BoxLayout(labels, BoxLayout.PAGE_AXIS));
componentWave.setBackground(new Color(255,255,255));
netWave.setBackground(new Color(255,255,255));
componentWave.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
netWave.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
componentWave.setPreferredSize(new Dimension(400,200));
netWave.setPreferredSize(new Dimension(400,200));
labels.add(wave);
labels.add(Box.createRigidArea(new Dimension(0,10)));
labels.add(chooseWave);
labels.add(componentLabel);
labels.add(componentWave);
labels.add(Box.createRigidArea(new Dimension(0,20)));
labels.add(netLabel);
labels.add(netWave);
add(labels);
}
}
Window is intended to be a 'main GUI class' and Sliders is supposed to inherit (?) from it.
Nope: this is a misuse of inheritance and will only lead to problems since the Windows instance that Sliders inherently is, is completely distinct from the displayed Windows instance. What you need to do is to pass references.
For example, the following code uses outside classes for the JButton and JMenuItem Actions (Actions are like ActionListeners on steroids), and uses a class that holds a JSlider that allows itside classes to attach listeners to the slider.
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Foo extends JPanel {
private static final long serialVersionUID = 1L;
private Action helloAction = new HelloAction("Hello", KeyEvent.VK_H);
private Action exitAction = new ExitAction("Exit", KeyEvent.VK_X);
private JMenuBar menuBar = new JMenuBar();
private JTextField sliderValueField = new JTextField(10);
private Bar bar = new Bar();
public Foo() {
sliderValueField.setEditable(false);
sliderValueField.setFocusable(false);
add(new JButton(helloAction));
add(new JButton(exitAction));
add(new JLabel("Slider Value: "));
add(sliderValueField);
add(bar);
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(new JMenuItem(exitAction));
fileMenu.add(new JMenuItem(helloAction));
menuBar.add(fileMenu);
bar.addSliderListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
int sliderValue = bar.getSliderValue();
sliderValueField.setText(String.valueOf(sliderValue));
}
});
}
public JMenuBar getJMenuBar() {
return menuBar;
}
private static void createAndShowGui() {
Foo mainPanel = new Foo();
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setJMenuBar(mainPanel.getJMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class HelloAction extends AbstractAction {
public HelloAction(String name, int mnemonic) {
super(name); // sets name property and gives button its title
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello!");
}
}
class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
if (win == null) {
// if no window, then a JMenuItem held in a JPopupMenu
JPopupMenu popup = (JPopupMenu) component.getParent();
component = popup.getInvoker();
win = SwingUtilities.getWindowAncestor(component);
}
win.dispose();
}
}
class Bar extends JPanel {
private JSlider slider = new JSlider(0, 100, 50);
public Bar() {
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setSnapToTicks(true);
setBorder(BorderFactory.createTitledBorder("Slider Panel"));
add(slider);
}
public int getSliderValue() {
return slider.getValue();
}
// one way to let outside classes listen for changes
public void addSliderListener(ChangeListener listener) {
slider.addChangeListener(listener);
}
}
You ask about decimal labels, and yes this can be done but requires use of a label table. For example,
JSlider slider = new JSlider(0, 100, 50);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(2);
Dictionary<Integer, JLabel> labels = new Hashtable<>();
for (int i = 0; i <= 100; i += 20) {
labels.put(i, new JLabel(String.format("%.1f", i / 200.0)));
}
slider.setLabelTable(labels);
Which displays as:
You would also have to translate the value back from int to its corresponding floating point number.
I am trying to build a register, so that when a button is clicked, a new entry appears on a table. Ideally, I am looking to build a table on the left side of the screen, with two rows and new column appears when the button is clicked. I want the table to have a fixed size, but it should be scrollable after a certain amount of entries. So far, I have created and formatted the JButton objects that I want to be clicked for a new entry to appear. I also know that I should use a JTable to pursue this.
How should I go about making this dynamic table?
Code So Far:
private void addRegister(JPanel pane) {
JPanel everythingPane = new JPanel();
JPanel pluPane = new JPanel();
Dimension button = new Dimension(200,150);
JTable pluTable = new JTable();
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.Y_AXIS));
//JPanel buttonPane = new JPanel (new FlowLayout (FlowLayout.LEFT));
JPanel subPane1 = new JPanel();
subPane1.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane2 = new JPanel();
subPane2.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane3 = new JPanel();
subPane3.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane4 = new JPanel();
subPane4.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane5 = new JPanel();
subPane5.setAlignmentX(LEFT_ALIGNMENT);
JPanel alignmentLayer = new JPanel();
JButton frappuccino = new JButton("Frappuccino");
JButton icedCoffee = new JButton("Iced Coffee");
frappuccino.setPreferredSize(button);
icedCoffee.setPreferredSize(button);
JButton arizona = new JButton("Arizona Green Tea");
JButton izze = new JButton("Izze");
arizona.setPreferredSize(button);
izze.setPreferredSize(button);
JButton snapple = new JButton("Snapple");
JButton gatorade = new JButton("Gatorade");
snapple.setPreferredSize(button);
gatorade.setPreferredSize(button);
JButton water = new JButton("Water");
JButton appleJuice = new JButton("Apple Juice");
water.setPreferredSize(button);
appleJuice.setPreferredSize(button);
JButton orangeJuice = new JButton("Orange Juice");
JButton mentos = new JButton("Mentos");
orangeJuice.setPreferredSize(button);
mentos.setPreferredSize(button);
JButton gum = new JButton("Gum");
JButton cliffBar = new JButton("Cliff Bar");
gum.setPreferredSize(button);
cliffBar.setPreferredSize(button);
JButton littleBites = new JButton("Little Bites");
JButton welchs = new JButton("Welch's Fruit Snacks");
littleBites.setPreferredSize(button);
welchs.setPreferredSize(button);
JButton fiberOneBar = new JButton("Fiber One Bar");
JButton fiberOneBrownie = new JButton("Fiber One Brownie");
fiberOneBar.setPreferredSize(button);
fiberOneBrownie.setPreferredSize(button);
JButton cheezeIts = new JButton("Cheeze Its");
JButton goldFish = new JButton("Gold Fish");
cheezeIts.setPreferredSize(button);
goldFish.setPreferredSize(button);
JButton teaBag = new JButton("Tea Bag");
JButton poptarts = new JButton("Poptarts");
teaBag.setPreferredSize(button);
poptarts.setPreferredSize(button);
JButton sampleButton = new JButton("Sample Button");
JButton sampleButton2 = new JButton("Sample Button");
sampleButton.setPreferredSize(button);
sampleButton2.setPreferredSize(button);
JButton sampleButton3 = new JButton("Sample Button");
JButton sampleButton4 = new JButton("Sample Button");
sampleButton3.setPreferredSize(button);
sampleButton4.setPreferredSize(button);
subPane1.add(frappuccino);
subPane1.add(icedCoffee);
subPane1.add(arizona);
subPane1.add(izze);
subPane2.add(snapple);
subPane2.add(gatorade);
subPane2.add(water);
subPane2.add(appleJuice);
subPane3.add(orangeJuice);
subPane3.add(mentos);
subPane3.add(gum);
subPane3.add(cliffBar);
subPane4.add(littleBites);
subPane4.add(welchs);
subPane4.add(fiberOneBar);
subPane4.add(fiberOneBrownie);
subPane5.add(cheezeIts);
subPane5.add(goldFish);
subPane5.add(teaBag);
subPane5.add(poptarts);
alignmentLayer.add(sampleButton);
alignmentLayer.add(sampleButton2);
alignmentLayer.add(sampleButton3);
alignmentLayer.add(sampleButton4);
buttonPane.add(subPane1);
buttonPane.add(subPane2);
buttonPane.add(subPane3);
buttonPane.add(subPane4);
buttonPane.add(subPane5);
buttonPane.add(Box.createRigidArea(new Dimension(5,100)));
buttonPane.add(alignmentLayer);
pluPane.add(pluTable);
everythingPane.add(pluPane);
everythingPane.add(buttonPane);
pane.add(everythingPane);
}
JTable is more commonly used in a way that adds rows, rather than columns. I re-factored this example to illustrate the basic idea below. Each time the button is clicked, a new row is added to the table's model, which updates the table itself.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
* #see https://stackoverflow.com/a/19472190/230513
* #see https://stackoverflow.com/a/7519403/230513
*/
public class TableAddTest extends JPanel {
private static final int N_ROWS = 8;
private static String[] header = {"ID", "String", "Number", "Boolean"};
private DefaultTableModel dtm = new DefaultTableModel(null, header) {
#Override
public Class<?> getColumnClass(int col) {
return getValueAt(0, col).getClass();
}
};
private JTable table = new JTable(dtm);
private JScrollPane scrollPane = new JScrollPane(table);
private JScrollBar vScroll = scrollPane.getVerticalScrollBar();
private int row;
private boolean isAutoScroll;
public TableAddTest() {
this.setLayout(new BorderLayout());
Dimension d = new Dimension(320, N_ROWS * table.getRowHeight());
table.setPreferredScrollableViewportSize(d);
for (int i = 0; i < N_ROWS; i++) {
addRow();
}
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
vScroll.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
isAutoScroll = !e.getValueIsAdjusting();
}
});
this.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("Add Row") {
#Override
public void actionPerformed(ActionEvent e) {
addRow();
}
}));
this.add(panel, BorderLayout.SOUTH);
}
private void addRow() {
char c = (char) ('A' + row++ % 26);
dtm.addRow(new Object[]{
Character.valueOf(c),
String.valueOf(c) + String.valueOf(row),
Integer.valueOf(row),
Boolean.valueOf(row % 2 == 0)
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableAddTest nlt = new TableAddTest();
f.add(nlt);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}