The JTextArea named txtaObservation is occupying five horizontal slots of its container's GridBagLayout. Its text should wrap by when it reaches the fifth slot, below the label named lblObservationLimit, however it is wrapping too soon, just about in the first slot. How do I make it wrap at the correct slot?
JDViewCustomer.java
package test2;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Objects;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JDViewCustomer extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private JTextArea txtaObservation;
private JPanel panelCustomerData;
private final CustomerData customerData;
private JLabel lblObservationLimit;
public JDViewCustomer(java.awt.Frame parent, boolean modal, CustomerData customerData) {
super(parent, modal);
this.customerData = Objects.requireNonNull(customerData);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
layoutCustomerDataSection();
addCustomerData();
initComponents();
}
public void layoutCustomerDataSection() {
panelCustomerData = new JPanel();
panelCustomerData.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelCustomerData.setBackground(Color.WHITE);
getContentPane().add(panelCustomerData);
GridBagLayout gbl_panelCustomerData = new GridBagLayout();
gbl_panelCustomerData.columnWidths = new int[]{58, 199, 38, 102, 27, 138, 0};
gbl_panelCustomerData.rowHeights = new int[]{0, 14, 0};
gbl_panelCustomerData.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelCustomerData.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelCustomerData.setLayout(gbl_panelCustomerData);
lblObservationLimit = new JLabel("Observation limit");
GridBagConstraints gbc_lblObservationLimit = new GridBagConstraints();
gbc_lblObservationLimit.insets = new Insets(0, 0, 5, 0);
gbc_lblObservationLimit.gridx = 5;
gbc_lblObservationLimit.gridy = 0;
panelCustomerData.add(lblObservationLimit, gbc_lblObservationLimit);
txtaObservation = new JTextArea("Observation text");
txtaObservation.setFont(new Font("Tahoma", Font.PLAIN, 11));
txtaObservation.setLineWrap(true);
txtaObservation.setWrapStyleWord(true);
GridBagConstraints gbc_txtaObservation = new GridBagConstraints();
gbc_txtaObservation.gridwidth = 5;
gbc_txtaObservation.anchor = GridBagConstraints.NORTHWEST;
gbc_txtaObservation.gridx = 1;
gbc_txtaObservation.gridy = 1;
panelCustomerData.add(txtaObservation, gbc_txtaObservation);
}
public void addCustomerData() {
txtaObservation.setText(customerData.getObservation());
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("View customer");
pack();
setLocationRelativeTo(getParent());
}
}
CustomerData.java
package test2;
public class CustomerData {
private final String observation;
public CustomerData(String observation) {
this.observation = observation;
}
public String getObservation() {
return observation;
}
}
Test2.java
package test2;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test2 {
private static void createAndShowGUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CustomerData customerData = new CustomerData("Testing a long observation text that should wrap only when reaching the observation limit.");
new JDViewCustomer(frame, true, customerData).setVisible(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Try this for JDViewCustomer.java -- comments are flagged with "// kwb". I didn't realize until just now that it was unofficially answered!
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Objects;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JDViewCustomer extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
private JTextArea txtaObservation;
private JPanel panelCustomerData;
private final CustomerData customerData;
private JLabel lblObservationLimit;
public JDViewCustomer(java.awt.Frame parent, boolean modal, CustomerData customerData) {
super(parent, modal);
this.customerData = Objects.requireNonNull(customerData);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
layoutCustomerDataSection();
addCustomerData();
initComponents();
}
public void layoutCustomerDataSection() {
panelCustomerData = new JPanel();
panelCustomerData.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 1, true), new EmptyBorder(10, 10, 10, 10)));
panelCustomerData.setBackground(Color.WHITE);
getContentPane().add(panelCustomerData);
GridBagLayout gbl_panelCustomerData = new GridBagLayout();
gbl_panelCustomerData.columnWidths = new int[]{58, 199, 38, 102, 27, 138, 0};
gbl_panelCustomerData.rowHeights = new int[]{0, 14, 0};
gbl_panelCustomerData.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panelCustomerData.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panelCustomerData.setLayout(gbl_panelCustomerData);
lblObservationLimit = new JLabel("Observation limit");
GridBagConstraints gbc_lblObservationLimit = new GridBagConstraints();
gbc_lblObservationLimit.insets = new Insets(0, 0, 5, 0);
gbc_lblObservationLimit.gridx = 5;
gbc_lblObservationLimit.gridy = 0;
// kwb set gridheight to total number of rows
gbc_lblObservationLimit.gridheight = 2;
panelCustomerData.add(lblObservationLimit, gbc_lblObservationLimit);
txtaObservation = new JTextArea("Observation text");
// kwb just to help view issue
txtaObservation.setBorder(BorderFactory.createLineBorder(Color.blue));
txtaObservation.setFont(new Font("Tahoma", Font.PLAIN, 11));
txtaObservation.setLineWrap(true);
txtaObservation.setWrapStyleWord(true);
GridBagConstraints gbc_txtaObservation = new GridBagConstraints();
gbc_txtaObservation.gridwidth = 5;
gbc_txtaObservation.anchor = GridBagConstraints.NORTHWEST;
// kwb fill all available horizontal space
gbc_txtaObservation.fill = GridBagConstraints.HORIZONTAL;
// kwb change to start in column 0, adjust as necessary
gbc_txtaObservation.gridx = 0;
gbc_txtaObservation.gridy = 1;
panelCustomerData.add(txtaObservation, gbc_txtaObservation);
}
public void addCustomerData() {
txtaObservation.setText(customerData.getObservation());
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("View customer");
pack();
setLocationRelativeTo(getParent());
}
}
Related
I'm trying to make a simple program where there is a text input field and a label, and when you input something to the field it stores the input as "testInput" and changes the label to that text. I'm using Eclipse's Window Builder plugin for this, and it has worked fine before. What happens now is it will take the text in, but wont send it back out to the jLabel. Here is my code:
package interest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestWin {
String testInput;
private JFrame frame;
private JTextField txtTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestWin window = new TestWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestWin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
txtTest = new JTextField();
//Change label when enter is pressed
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
txtTest.setText(testInput);
}
});
txtTest.setText("test");
GridBagConstraints gbc_txtTest = new GridBagConstraints();
gbc_txtTest.insets = new Insets(0, 0, 5, 0);
gbc_txtTest.fill = GridBagConstraints.HORIZONTAL;
gbc_txtTest.gridx = 5;
gbc_txtTest.gridy = 1;
frame.getContentPane().add(txtTest, gbc_txtTest);
txtTest.setColumns(10);
JLabel lblTest = new JLabel("test");
GridBagConstraints gbc_lblTest = new GridBagConstraints();
gbc_lblTest.gridx = 5;
gbc_lblTest.gridy = 4;
frame.getContentPane().add(lblTest, gbc_lblTest);
}
}
I'm sure I'm making a really simple mistake, so any help is appreciated!
Put
JLabel lblTest = new JLabel("test");
at the begining of initialize() (or anywhere above txtTest.addActionListener...), and then replace
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
txtTest.setText(testInput);
}
});
for
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
lblTest.setText(testInput); //This line was changed.
}
});
This is my SSCE (though in three seperate classes).
StartUp.java
public class Startup {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame gui = new MainFrame();
}
});
}
}
MainFrame.java
package gui;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class MainFrame {
private JFrame mainFrame;
private JMenuBar menuBar;
private JMenu menuRoboControl;
private JMenuItem menuItemStart;
private JMenuItem menuItemShutdown;
private JPanel cardPanel;
private final JPanel comListCard = new ComListCard();
public MainFrame() {
initComponents();
}
private void menuItemStartActionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) cardPanel.getLayout();
cardLayout.show(cardPanel, "selectPort");
}
private void menuItemShutdownActionPerformed(ActionEvent e) {
mainFrame.dispose();
System.exit(0);
}
private void initComponents() {
mainFrame = new JFrame();
menuBar = new JMenuBar();
menuRoboControl = new JMenu();
menuItemStart = new JMenuItem();
menuItemShutdown = new JMenuItem();
cardPanel = new JPanel();
//======== mainFrame ========
{
Container mainFrameContentPane = mainFrame.getContentPane();
mainFrameContentPane.setLayout(new BoxLayout(mainFrameContentPane, BoxLayout.X_AXIS));
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//======== menuBar ========
{
//======== menuRoboControl ========
{
menuRoboControl.setText("RoboControl");
//---- menuItemStart ----
menuItemStart.setText("Start Robot");
menuItemStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuItemStartActionPerformed(e);
}
});
menuRoboControl.add(menuItemStart);
//---- menuItemShutdown ----
menuItemShutdown.setText("Shutdown Robot");
menuItemShutdown.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuItemShutdownActionPerformed(e);
}
});
menuRoboControl.add(menuItemShutdown);
}
menuBar.add(menuRoboControl);
}
mainFrame.setJMenuBar(menuBar);
//======== cardPanel ========
{
cardPanel.setLayout(new CardLayout());
cardPanel.add(comListCard, "selectPort");
}
mainFrameContentPane.add(cardPanel);
mainFrame.setSize(835, 635);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
}
}
ComListCard.java
package gui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ComListCard extends JPanel {
private JTextArea portInfo;
private JScrollPane scrollPane1;
private JList<String> portList;
private JButton selectPort;
public ComListCard() {
initComponents();
}
public void initComponents() {
portInfo = new JTextArea();
scrollPane1 = new JScrollPane();
portList = new JList<>();
selectPort = new JButton();
//======== comListCard ========
{
this.setLayout(new GridBagLayout());
((GridBagLayout) this.getLayout()).columnWidths = new int[]{298, 214, 0, 0};
((GridBagLayout) this.getLayout()).rowHeights = new int[]{0, 0, 0, 0, 86, 220, 0, 0, 0};
((GridBagLayout) this.getLayout()).columnWeights = new double[]{0.0, 0.0, 1.0, 1.0E-4};
((GridBagLayout) this.getLayout()).rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0E-4};
//---- portInfo ----
portInfo.setText("Select the port connected to your XBee. If you do not know what port it is connected to, check your Device Manager.");
portInfo.setLineWrap(true);
portInfo.setWrapStyleWord(true);
portInfo.setOpaque(false);
portInfo.setEnabled(false);
portInfo.setEditable(false);
portInfo.setBorder(null);
this.add(portInfo, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//======== scrollPane1 ========
{
//---- portList ----
portList.setModel(new AbstractListModel<String>() {
String[] values = {
"1",
"2",
"3",
"4"
};
#Override
public int getSize() {
return values.length;
}
#Override
public String getElementAt(int i) {
return values[i];
}
});
scrollPane1.setViewportView(portList);
}
this.add(scrollPane1, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- selectPort ----
selectPort.setText("Select");
this.add(selectPort, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
}
}
}
Now some information on the problem. GUI works fine, purely about the CardLayout. As you can see I created a main window with a JPanel inside acting as the holder of the card. I created a card and have added it too to CardLayout. But it already appears from the start of the program while it should only appear after pressing the button (referring to the actionlistener where I put .show(..).
Any help appreciated. Not in a hurry either.
A CardLayout is designed to "hold" multiple cards (panels), but only one card will ever be displayed at a time. The key is that "one" of the panels is always displayed. So the CardLayout is functioning properly.
If you has an application that needs to dynamically display an panel on a frame then you must add the panel at run time. In this case the basic logic would be:
panel.add(...);
panel.revalidate();
panel.repaint();
With the above approach, space is not reserved on the frame for the panel when the frame is initially displayed (so you may also need to pack() the frame to make sure the panel is visible).
If you really want to see an empty space for your card panel when the frame is displayed, then you could simply create a panel with no components added to it and then add this panel to your CardLayout. Then when you invoke the show() method, you will swap in your panel with the components.
Im new to GUI's in Java and having a hell of a time understanding this:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
public class Main extends JFrame {
private JPanel contentPane;
static JPanel panel;
static JScrollPane scrollPane;
static JButton btnStart;
private static String compTestArray[];
static Integer indexer = 0;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 739, 456);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnStart = new JButton("Start");
btnStart.setBounds(10, 379, 89, 23);
btnStart.addActionListener(new ButtonListener());
contentPane.add(btnStart);
panel = new JPanel();
panel.setBounds(10, 11, 513, 359);
contentPane.add(panel);
scrollPane = new JScrollPane(panel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
scrollPane.setBounds(10, 11, 633, 359);
contentPane.add(scrollPane);
compTestArray = new String[2];
compTestArray[0] = "172.16.98.3";
compTestArray[1] = "172.16.98.6";
}
static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
//String labelText = "Computer Name\tTest Name\tIteration\tPass\tFail\tCrashes\tStart\tStop";
//labelText = labelText.replaceAll("\t", " ");
listOfLabels.add(new JLabel("Computer"));
for(int ix = 0; ix < compTestArray.length; ix++){
// Clear panel
panel.removeAll();
//labelText = compTestArray[indexer] + "\tKPI_1_1_1_1\t" + ix + "/20\t1\t\t0\t\t0\t\t12:00\t12:30";
//labelText = labelText.replaceAll("\t", " ");
listOfLabels.add(new JLabel(compTestArray[indexer]));
System.out.println("indexer is " + indexer);
// Create constraints
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer+2; i++) {
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.weightx = 0;
labelConstraints.insets = new Insets(10, 10, 10, 10);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
// Repaint the GUI
scrollPane.validate();
} // Close for loop
// Disable Start button
btnStart.setEnabled(false);
} // Close public void actionPerformed(ActionEvent arg0)
} // Close static class ButtonListener implements ActionListener
}
Output:
I don't know why my scroll bar in text area doesn't work. I found many solutions in internet, but no 1 helped for me.
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
I found that can't be Panel's layout Absolute, if I change It to Group layout the same.
What's wrong? Could you help me? Thank you.
UPDATED:
package lt.kvk.i3_2.kalasnikovas_stanislovas;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextPane;
import javax.swing.DropMode;
import javax.swing.JFormattedTextField;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JMenuItem;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import java.awt.SystemColor;
import java.awt.Font;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JScrollBar;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JToolBar;
public class KDVizualizuotas {
private JFrame frmInformacijaApieMuzikos;
private JTextField txtStilius;
private JTextArea textArea1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KDVizualizuotas window = new KDVizualizuotas();
window.frmInformacijaApieMuzikos.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public KDVizualizuotas() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmInformacijaApieMuzikos = new JFrame();
frmInformacijaApieMuzikos.setResizable(false);
frmInformacijaApieMuzikos.setIconImage(Toolkit.getDefaultToolkit().getImage(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/Sidebar-Music-Blue-icon.png")));
frmInformacijaApieMuzikos.setTitle("Muzikos stiliai");
frmInformacijaApieMuzikos.setBounds(100, 100, 262, 368);
frmInformacijaApieMuzikos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtStilius = new JTextField();
txtStilius.setBounds(10, 34, 128, 20);
txtStilius.setColumns(10);
JButton btnIekoti = new JButton("Ie\u0161koti");
btnIekoti.setBounds(146, 36, 89, 19);
btnIekoti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// textArea1.append(txtStilius.getText()+"\n");
// txtStilius.getText();
Scanner input = new Scanner(System.in);
try {
FileReader fr = new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Stiliai.txt");
BufferedReader br = new BufferedReader(fr);
String stiliuSarasas;
while((stiliuSarasas = br.readLine()) != null) {
System.out.println(stiliuSarasas);
textArea1.append(stiliuSarasas+"\n");
}
fr.close();
}
catch (IOException e) {
System.out.println("Error:" + e.toString());
}
}
});
JPanel panel = new JPanel();
panel.setBounds(10, 65, 224, 243);
panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panel.setBackground(SystemColor.text);
JLabel lblveskiteMuzikosStili = new JLabel("\u012Eveskite muzikos stili\u0173:");
lblveskiteMuzikosStili.setBounds(10, 14, 222, 14);
frmInformacijaApieMuzikos.getContentPane().setLayout(null);
panel.setLayout(null);
frmInformacijaApieMuzikos.getContentPane().add(panel);
JLabel lblInformacijaApieMuzikos = new JLabel("Informacija apie muzikos stili\u0173:");
lblInformacijaApieMuzikos.setBounds(12, 3, 190, 14);
panel.add(lblInformacijaApieMuzikos);
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
frmInformacijaApieMuzikos.getContentPane().add(txtStilius);
frmInformacijaApieMuzikos.getContentPane().add(btnIekoti);
frmInformacijaApieMuzikos.getContentPane().add(lblveskiteMuzikosStili);
JMenuBar menuBar = new JMenuBar();
frmInformacijaApieMuzikos.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mntmExit.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/exitas.png")));
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmHelp = new JMenuItem("Help");
mnHelp.add(mntmHelp);
JMenu mnAbout = new JMenu("About");
menuBar.add(mnAbout);
JMenuItem mntmAbout = new JMenuItem("About");
mntmAbout.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/questionmark.png")));
mnAbout.add(mntmAbout);
}
}
You need to add the component you want to be contained within the scroll pane to it.
You can do this via the JScrollPane's constructor or JScrollPane#setViewportView method
public class ScrollPaneTest {
public static void main(String[] args) {
new ScrollPaneTest();
}
public ScrollPaneTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JPanel bigPane = new JPanel();
bigPane.setBackground(Color.BLUE);
// This is not recommended, but is used for demonstration purposes
bigPane.setPreferredSize(new Dimension(1024, 768));
JScrollPane scrollPane = new JScrollPane(bigPane);
scrollPane.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Updated with proper layout
You should avoid null or absolute layouts, they will only hurt you in the long wrong.
You may also find How to use Scroll Panes of use
public class BadLayout {
public static void main(String[] args) {
new BadLayout();
}
public BadLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField searchField;
private JButton searchButton;
private JTextArea searchResults;
public TestPane() {
setLayout(new BorderLayout());
searchResults = new JTextArea();
searchResults.setLineWrap(true);
searchResults.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(searchResults);
JPanel results = new JPanel(new BorderLayout());
results.setBorder(new EmptyBorder(4, 8, 8, 8));
results.add(scrollPane);
add(results);
JPanel search = new JPanel(new GridBagLayout());
search.setBorder(new EmptyBorder(8, 8, 4, 8));
searchField = new JTextField(12);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.insets = new Insets(0, 0, 0, 4);
search.add(searchField, gbc);
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
search.add(searchButton, gbc);
add(search, BorderLayout.NORTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
}
}
In my application i have add some music to my main Frame. If i click a Jbutton on this Frame it will open a new Jframe but my problem is when i open the new JFrame the music still continue with playing but i want it to stop when the new Jframe is open
Code of my main class:
package View;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import Controller.HomeController;
import music.PlaySound;
public class Home extends JFrame {
private JLabel label, label1, label2;
private JPanel panel;
private JButton logo, logo1, logo2, logo3, logo4, logo5, selectie;
private Container window = getContentPane();
private HomeController Controller;
public Home (){
initGUI();
}
public void addHomeListener(ActionListener a){
selectie.addActionListener(a);
}
public void initGUI(){
PlaySound sound = new PlaySound();
setLayout(null);
setTitle("");
setPreferredSize(new Dimension(800,600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.WHITE);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(267, 0, 266, 800);
label1.setBackground(Color.RED);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(533, 0, 266, 800);
label2.setBackground(Color.WHITE);
label2.setOpaque(true);
window.add(label2);
logo = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
logo.setBorderPainted(false);
logo.setBounds(40, 150, 188, 188);
label1.add(logo);
logo1 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo1.setBorderPainted(false);
logo1.setBounds(10, 50, 82, 82);
label1.add(logo1);
logo2 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo2.setBorderPainted(false);
logo2.setBounds(92, 20, 82, 82);
label1.add(logo2);
logo3 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo3.setBorderPainted(false);
logo3.setBounds(174, 50, 82, 82);
label1.add(logo3);
logo4 = new JButton(new ImageIcon("../Ajax/src/img/shirt.png"));
logo4.setBorderPainted(false);
logo4.setBounds(50, 50, 135, 182);
label.add(logo4);
logo5 = new JButton(new ImageIcon("../Ajax/src/img/uitshirt.png"));
logo5.setBorderPainted(false);
logo5.setBounds(65, 50, 138, 190);
label2.add(logo5);
selectie = new JButton("Selectie");
selectie.setBounds(60, 500, 99, 25);
selectie.setActionCommand("selectie");
label.add(selectie);
pack();
Controller = new HomeController(this);
addHomeListener(Controller);
setVisible(true);
}
public static void main(String... args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Home();
}
});
}
}
Code of my new opened Jframe when click on button:
package View;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import music.PlaySound;
import Controller.HomeController;
public class Selectie extends JFrame{
private JLabel label, label1, label2;
private JButton keeper;
private JPanel panel;
private Container window = getContentPane();
public Selectie()
{
initGUI();
}
public void initGUI()
{
setLayout(null);
setTitle("");
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.RED);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(266, 0, 266, 800);
label1.setBackground(Color.BLACK);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(532, 0, 266, 800);
label2.setBackground(Color.RED);
label2.setOpaque(true);
window.add(label2);
keeper = new JButton("Kenneth Vermeer");
keeper.setBounds(10, 50, 82, 82);
label.add(keeper);
}
}
Code of my music class:
package music;
import java.io.*;
import javax.sound.sampled.*;
import Controller.HomeController;
import View.Home;
public class PlaySound
{
{
sound = new File("../Ajax/src/sound/Sound.wav"); // Write you own file location here and be aware that it need to be an .wav file
new Thread(play).start();
}
static File sound;
static boolean muted = false; // This should explain itself
static float volume = 100.0f; // This is the volume that goes from 0 to 100
static float pan = 0.0f; // The balance between the speakers 0 is both sides and it goes from -1 to 1
static double seconds = 0.0d; // The amount of seconds to wait before the sound starts playing
static boolean looped_forever = false; // It will keep looping forever if this is true
static int loop_times = 0; // Set the amount of extra times you want the sound to loop (you don't need to have looped_forever set to true)
static int loops_done = 0; // When the program is running this is counting the times the sound has looped so it knows when to stop
final static Runnable play = new Runnable() // This Thread/Runnabe is for playing the sound
{
public void run()
{
try
{
// Check if the audio file is a .wav file
if (sound.getName().toLowerCase().contains(".wav"))
{
AudioInputStream stream = AudioSystem.getAudioInputStream(sound);
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)
{
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2,
format.getChannels(),
format.getFrameSize() * 2,
format.getFrameRate(),
true);
stream = AudioSystem.getAudioInputStream(format, stream);
}
SourceDataLine.Info info = new DataLine.Info(
SourceDataLine.class,
stream.getFormat(),
(int) (stream.getFrameLength() * format.getFrameSize()));
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
line.open(stream.getFormat());
line.start();
// Set Volume
FloatControl volume_control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
volume_control.setValue((float) (Math.log(volume / 100.0f) / Math.log(10.0f) * 20.0f));
// Mute
BooleanControl mute_control = (BooleanControl) line.getControl(BooleanControl.Type.MUTE);
mute_control.setValue(muted);
FloatControl pan_control = (FloatControl) line.getControl(FloatControl.Type.PAN);
pan_control.setValue(pan);
long last_update = System.currentTimeMillis();
double since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
// Wait the amount of seconds set before continuing
while (since_last_update < seconds)
{
since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
}
System.out.println("Playing!");
int num_read = 0;
byte[] buf = new byte[line.getBufferSize()];
while ((num_read = stream.read(buf, 0, buf.length)) >= 0)
{
int offset = 0;
while (offset < num_read)
{
offset += line.write(buf, offset, num_read - offset);
}
}
line.drain();
line.stop();
if (looped_forever)
{
new Thread(play).start();
}
else if (loops_done < loop_times)
{
loops_done++;
new Thread(play).start();
}
}
}
catch (Exception ex) { ex.printStackTrace(); }
}
};
}
Code of my button click class:
package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import music.PlaySound;
import View.Home;
import View.Selectie;
public class HomeController implements ActionListener {
private Home home;
public HomeController(Home home){
this.home = home;
}
public void actionPerformed (ActionEvent e){
home.dispose();
Selectie selectie = new Selectie();
selectie.setVisible(true);
}
}
You could set a variable in PlaySound before opening the new frame to indicate that the playback should stop.
static boolean shouldStop = false;
static void stopPlayback() {
shouldStop = true;
}
In the inner loop of PlaySound you quit the loop and the thread terminates.
while ((num_read = stream.read(buf, 0, buf.length)) >= 0) {
if ( shouldStop ) {
break;
}
...
}