put two vertical JSplitPane on a frame java - java

I am a new java programmer and I use stackoverflow since my begin. I code a little "game", and it is a text-based game. Well, i begin a graphical interface, to case the text, and i would have this configuration
Basically, it is a double separation, with 3 horizontals elements. Actually, I have this:
and i want a separation
I have tried to put an other split pane on the top of the first one, like this:
package sample;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
class Fenetresaisie extends JFrame {
public static class Fenetre {
public final static int HT = 1024;
public final static int LG = 758;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame F = new JFrame("CORONAZE");
F.setExtendedState(JFrame.MAXIMIZED_BOTH);
F.setSize(HT, LG);
F.setVisible(true);
F.addWindowListener(new gestionFenetre());
ImageIcon icone = new ImageIcon("images.jpg");
JLabel image = new JLabel(icone);
JTextField textField = new JTextField();
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent e) {
textField.getText();
e.getKeyChar();
}
});
JLabel label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
panel.add(label);
JSplitPane topJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, label, textField);
// topJSplitPane.setDividerLocation(400);
JSplitPane bottomJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, topJSplitPane, textField );
//i added it to have a double separation, but it give 2 sticked splitpane
F.add(topJSplitPane, BorderLayout.CENTER);
F.add(bottomJSplitPane, BorderLayout.SOUTH);
F.setVisible(true);
}
}
static class gestionFenetre extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
But it gives me two sticked splitpane :-/
Can you help me please? I hope you understand my message, because I learn English. Contact me below if you want a next phase to this issue, thanks! ^^ Here is the actual graphical test java class:
package sample;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
class Fenetresaisie extends JFrame {
public static class Fenetre {
public final static int HT = 1024;
public final static int LG = 758;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame F = new JFrame("CORONAZE");
F.setExtendedState(JFrame.MAXIMIZED_BOTH);
F.setSize(HT, LG);
F.setVisible(true);
F.addWindowListener(new gestionFenetre());
ImageIcon icone = new ImageIcon("images.jpg");
JLabel image = new JLabel(icone);
JTextField textField = new JTextField();
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent e) {
textField.getText();
e.getKeyChar();
}
});
JLabel label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
panel.add(label);
JSplitPane topJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, label, textField);
topJSplitPane.setDividerLocation(400);
// JSplitPane bottomJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, topJSplitPane, textField );
//i added it to have a double separation, but it give 2 sticked splitpane
F.add(topJSplitPane, BorderLayout.CENTER);
// F.add(bottomJSplitPane, BorderLayout.SOUTH);
F.setVisible(true);
}
}
static class gestionFenetre extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}

You wrote in your question
I am a new java programmer and I use stackoverflow since my begin
I really think that the way to learn Swing programming is to follow a learning curve that starts with the basics and gradually progresses. Everybody has his preferred way to learn, for example by attending a course or watching a video or reading a book. Personally I prefer books. If you do too, then I can recommend a few.
You also wrote in your question
I code a little "game"
I would say that is a very ambitious project for a beginner. While I'm sure that there are people who learn best by starting off with ambitious projects, I would say they are in the minority.
That said, the key to correctly implementing your GUI is having a deep understanding of how Swing works, in particular layout managers and Component sizes as well as at what point in the code can you set those Component sizes.
The below code will initially display your desired GUI, since I understand, from your question, that that is what you are trying to accomplish now.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class WindowCapture extends WindowAdapter implements Runnable {
private JFrame frame;
private JLabel label;
private JSplitPane splitPane;
private JSplitPane topPane;
#Override // java.lang.Runnable
public void run() {
showGui();
}
#Override // java.awt.event.WindowAdapter
public void windowOpened(WindowEvent event) {
int height = event.getWindow().getHeight();
splitPane.setDividerLocation(0.7);
double high = height * 0.7;
height = (int) Math.rint(high);
high = height * 0.8;
height = (int) Math.rint(high);
label.setPreferredSize(new Dimension(event.getWindow().getWidth(), height));
}
private JTextField createBottomPane() {
JTextField textField = new JTextField(20);
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
return textField;
}
private JSplitPane createSplitPane() {
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, createTopPane(), createBottomPane());
splitPane.setDividerLocation(0.4);
return splitPane;
}
private JSplitPane createTopPane() {
label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
topPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
label,
new JPanel());
topPane.setDividerLocation(0.9);
return topPane;
}
public void showGui() {
frame = new JFrame("Window Capture");
frame.addWindowListener(this);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.add(createSplitPane());
frame.setVisible(true);
}
/**
* Start here!
*/
public static void main(String[] args) {
EventQueue.invokeLater(new WindowCapture());
}
}
Here is a screen capture of the running app.

Related

Java - how to zoom in/zoom out text in JTextArea

I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}

GridLayout JButton JOptionPane with ActionListener for each button

I am making a dating game in the style of the Japanese dating game with pictures and responses for fun and practice. I am trying to have a JOptionPane message dialog show up for each button in a grid layout as a response to each option. In this way it's like a logic tree. I am not used to using action listener as I am somewhat of a beginner. Here is my code. I am just not used to the syntax of doing this.
Can anyone help me?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.*;
//Implementations of packages
public class NestedPanels extends JPanel {
private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
private static final int TITLE_POINTS = 3; //number of objects in text box
public NestedPanels() { //implemeted class
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
for (String btnText : BTN_TEXTS) { //BTN TEXT button titles linked to string btnText label
southBtnPanel.add(new JButton(btnText)); //add btnText label
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Review the following to get an idea of how to add action listener to buttons.
Please note the comments:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class NestedPanels extends JPanel {
private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
//never used : private static final int TITLE_POINTS = 3;
public NestedPanels() {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1));
for (String btnText : BTN_TEXTS) {
JButton b = new JButton(btnText);
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonClicked(e);//when button clicked, invoke method
}
});
//alternative much shorter way to add action listener:
//b.addActionListener(e -> buttonClicked());
southBtnPanel.add(b);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
//this adds Box to the default BorderLayout.CENTER position
add(Box.createRigidArea(new Dimension(600, 600)));
add(southBtnPanel, BorderLayout.SOUTH);
}
//respond to button clicked
private void buttonClicked(ActionEvent e) {
String msg = ((JButton)e.getSource()).getActionCommand()+" pressed" ;
JOptionPane.showMessageDialog(this, msg ); //display button Action
}
private static void createAndShowGui() {
NestedPanels mainPanel = new NestedPanels();
JFrame frame = new JFrame("Date Sim 1.0");
//no need to invoke twice frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//no need to invoke twice frame.pack();
//no need to invoke twice frame.setVisible(true);
frame.getContentPane().add(mainPanel);
/*
* when posting images, use web resources that anyone can access
*
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
*this adds label to the default BorderLayout.CENTER position, which is already taken by
*the Box. Only one (last) component will be added
mainPanel.add(label);
*
*/
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//remove all code which is not essential to the question
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
but I have already instantiated a parent class of extending the jpanel
Did you look at the example code provided in the tutorial???
The example there "
... extends JFrame implements ActionListener
So all you need is:
... extends JPanel implements ActionListener
Or in case you need multiple ActionListeners the more flexible approach to create a custom class.
You can use an "annonymous inner class" for the ActionListener. Something like:
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
String text = button.getText();
Window window = SwingUtilities.windowForComponent(button);
JOptionPane.showMessageDialog(window, text);
}
};
Then when you create the button you would do:
for (String btnText : BTN_TEXTS)
{
JButton button = new JButton( btnText );
button.addActionListener( al );
southBtnPanel.add( button );
}

How do you add a XChart PieChart to an existing Java GUI?

Recently I asked a question similar to this but didn't give enough info and my code was too long for a code review. I have written a new file with the same bare bones as my previous post. Here I'm reaching the same issues once again.
When I attempt to click the Show Graph button, I get the following Error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.knowm.xchart.XChartPanel.<init>(XChartPanel.java:65)
at testMain$1.actionPerformed(testMain.java:78)"
Here is my code:
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.DefaultTableModel;
import org.knowm.xchart.PieChart;
import org.knowm.xchart.PieChartBuilder;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XChartPanel;
import org.knowm.xchart.style.PieStyler.AnnotationType;
import org.knowm.xchart.style.Styler.ChartTheme;
import org.knowm.xchart.style.Styler.LegendPosition;
public class testMain extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel gui, choiceBar,insertPanel;
private XChartPanel chartPanel;
private JButton showGraph;
private PieChart chart;
public testMain() {
this.setTitle("Test Frame");
this.setSize(500, 500);
JPanel gui = new JPanel(new BorderLayout());
//choice bar testing
choiceBar = new JPanel(new FlowLayout());
// Radio button group
JRadioButton halfhalf = new JRadioButton("Split half");
JRadioButton quarters = new JRadioButton("Split quarters");
ButtonGroup group1 = new ButtonGroup();
group1.add(halfhalf); group1.add(quarters);
//add to choice bar
choiceBar.add(halfhalf); choiceBar.add(quarters);
//Side panel for inserting user values
insertPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(insertPanel);
groupLayout.setAutoCreateGaps(true);
groupLayout.setAutoCreateContainerGaps(true);
//Display Button
JButton showGraph = new JButton("Show Graph");
JLabel showGraphLabel = new JLabel("Finish");
//JTextfield for inserting value
JTextField value = new JTextField("value");
JLabel valueLabel = new JLabel("Insert value here:");
// Grouping JTextFields
GroupLayout.SequentialGroup groupH = groupLayout.createSequentialGroup();
GroupLayout.SequentialGroup groupV = groupLayout.createSequentialGroup();
groupH.addGroup(groupLayout.createParallelGroup().addComponent(valueLabel).addComponent(showGraphLabel));
groupH.addGroup(groupLayout.createParallelGroup().addComponent(value).addComponent(showGraph));
groupLayout.setHorizontalGroup(groupH);
groupV.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(valueLabel).addComponent(value));
groupV.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(showGraphLabel).addComponent(showGraph));
groupLayout.setVerticalGroup(groupV);
showGraph.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String valueText = value.getText();
double valueAmount = Double.parseDouble(valueText);
if (halfhalf.isSelected()) {
chartPanel = new XChartPanel(chart);
chart = new PieChartBuilder().width(600).height(400).title("Split By").theme(ChartTheme.GGPlot2).build();
chart.getStyler().setLegendVisible(false);
chart.getStyler().setAnnotationType(AnnotationType.LabelAndPercentage);
chart.getStyler().setAnnotationDistance(1.15);
chart.getStyler().setPlotContentSize(.7);
chart.getStyler().setStartAngleInDegrees(90);
chart.addSeries("1", valueAmount/2);
chart.addSeries("2", valueAmount/2);
new SwingWrapper(chart).displayChart();
gui.add(chartPanel, BorderLayout.SOUTH);
gui.validate();
gui.repaint();
}
else {
chartPanel = new XChartPanel(chart);
chart = new PieChartBuilder().width(600).height(400).title("Split By").theme(ChartTheme.GGPlot2).build();
chart.getStyler().setLegendVisible(false);
chart.getStyler().setAnnotationType(AnnotationType.LabelAndPercentage);
chart.getStyler().setAnnotationDistance(1.15);
chart.getStyler().setPlotContentSize(.7);
chart.getStyler().setStartAngleInDegrees(90);
chart.addSeries("1",valueAmount/4);
chart.addSeries("2", valueAmount/4);
chart.addSeries("3", valueAmount/4);
chart.addSeries("4", valueAmount/4);
new SwingWrapper(chart).displayChart();
gui.add(chartPanel, BorderLayout.SOUTH);
gui.validate();
gui.repaint();
}
}
});
// add to gui
gui.add(choiceBar, BorderLayout.NORTH);
gui.add(insertPanel, BorderLayout.WEST);
this.add(gui);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
testMain frame = new testMain();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
});
}
}
`
I'm trying to write a Java GUI where once the user clicks the button, the graph shows up on the same GUI. I still would like to implement this using nested layouts as I like the clean look. Someone mentioned that I could use cardLayout but I think that would be too cluttered.
Thanks, and any help is apprecaited.

Changing JScrollPane height in Swing

I failed to change the height of JPanel or JScrollPane to make more lines to appear, I used GridLayout. It seems that, every component in it should have the same size even when I use setSize(). Should I use another layout?
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Main {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private imagePanel image;
JTextField textField = new JTextField(20);
public Main() throws IOException{
prepareGUI();
}
class imagePanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
try {
BufferedImage image = ImageIO.read(new File("file.jpg"));
g.drawImage(image, 170, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException{
Main swingControlDemo = new Main();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,500);
GridLayout gridlayout = new GridLayout(4, 1);
gridlayout.setVgap(1);
mainFrame.setLayout(gridlayout);
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
JScrollPane scroller = new JScrollPane(statusLabel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
image = new imagePanel();
image.setLayout(new FlowLayout());
// mainFrame.add(headerLabel);
mainFrame.add(image);
mainFrame.add(controlPanel);
mainFrame.add(scroller);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
JButton okButton = new JButton("reload");
JButton submitButton = new JButton("Submit");
JButton cancelButton = new JButton("Cancel");
okButton.setActionCommand("reload");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
//controlPanel.add(cancelButton);
controlPanel.add(textField);
System.out.println("---------------------");
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "reload" )) {
statusLabel.setText(convertToMultiline("Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8\nLine9\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine\nLine2\nLine3\nLine"));
}
else {
statusLabel.setText("Submit Button clicked.");
}
}
}
public static String convertToMultiline(String orig)
{
return "<html>" + orig.replaceAll("\n", "<br>");
}
}
The GUI need to look like this
I want to remove the large vertical gaps between the componets, and the jLabel should use that space
Well in your comment you say you want the label to use the space. But in your picture you show the text area with all the space. How can we answer a question when you give us conflicting requirements? Be specific and accurate when describing a problem.
In any case, the default layout of a JFrame is a BorderLayout so you would probably start with that.
Then the component that you want to grow/shrink as the frame is resized should be added to the CENTER of the frame.
Then you create a second panel to contain your other components. This panel would then be added to either the PAGE_START or PAGE_NORTH of the frame depending on your exact requirement.
The layout manager of this panel can then be whatever your want. Maybe a GridLayout, or a GridBagLayout or a vertical BoxLayout.
Read the section from the Swing tutorial on Layout Managers for more information and working examples. The key point is you create nest panels each with a different layout manager to achieve your layout.

How Do I use KeyListener to Display Different Strings Depending on Which Key is Pressed?

Take it easy on me, I'm pretty new to Java programming in general, especially swing, and I'm trying to learn the basics of GUI programming.
I want to be able to prompt the user to enter a certain key into a text box and then click a button to display a string of text based on what key they enter. This is what I have so far:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LeeSinAbilities extends JFrame
{
private JLabel leeSin;
private JTextField ability;
private JButton c;
private JLabel aName;
private static final long serialVersionUID = 1L;
public LeeSinAbilities()
{
super("Lee Sin's Abilities");
setLayout(new FlowLayout());
setResizable(true);
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel leeSin = new JLabel("Enter an ability key to see Lee Sin's ability names! (q, w, e, r)");
add(leeSin);
JTextField ability = new JTextField("Enter abilities here: ", 1);
add(ability);
JButton go = new JButton("Get Ability Name");
add(go);
JLabel aName = new JLabel("");
add(aName);
event e = new event();
go.addActionListener(e);
}
public static void main(String [] args){
new LeeSinAbilities().setVisible(true);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
String abilityName = ability.getText();
if(abilityName.equalsIgnoreCase("q")){
aName.setText("Sonic Wave / Resonating Strike");
}
else if(abilityName.equalsIgnoreCase("w")){
aName.setText("Safeguard / Iron Will");
}
else if(abilityName.equalsIgnoreCase("e")){
aName.setText("Tempest / Cripple");
}
else if(abilityName.equalsIgnoreCase("r")){
aName.setText("Dragon's Rage");
}
else
aName.setText("Brutha please -_-...q, w, e, or r!");
}
}
}
I realise ActionListener is not the correct event to use, I'm just not sure what to put there yet (I'm guessing KeyListener.) All comments / suggestions are highly appreciated.
The first issue (which I assume is NullPointerException) is due to the fact that you are shadowing your variables...
public class LeeSinAbilities extends JFrame
{
//...
// This is a instance variable named ability
private JTextField ability;
//...
public LeeSinAbilities()
{
//...
// This is a local variable named ability , which
// is now shadowing the instance variable...
JTextField ability = new JTextField("Enter abilities here: ", 1);
//...
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
// This will be `null` as it's referencing the
// instance variable...
String abilityName = ability.getText();
//...
}
}
}
So instead of using...
JTextField ability = new JTextField("Enter abilities here: ", 1);
You should be using...
ability = new JTextField("Enter abilities here: ", 1);
This will prevent the NullPointerException from occurring in you actionPerformed method
Updated
Now, if you want to respond to key events, the best approach is to use the Key Bindings API, for example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class KeyPrompt {
public static void main(String[] args) {
new KeyPrompt();
}
public KeyPrompt() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel aName;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JLabel("Enter an ability key to see Lee Sin's ability names! (q, w, e, r)"), gbc);
aName = new JLabel("");
add(aName, gbc);
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0), "QAbility");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "WAbility");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_E, 0), "EAbility");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0), "RAbility");
am.put("QAbility", new MessageAction(aName, "Sonic Wave / Resonating Strike"));
am.put("WAbility", new MessageAction(aName, "Safeguard / Iron Will"));
am.put("EAbility", new MessageAction(aName, "Tempest / Cripple"));
am.put("RAbility", new MessageAction(aName, "Dragon's Rage"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
public class MessageAction extends AbstractAction {
private final String msg;
private final JLabel msgLabel;
public MessageAction(JLabel msgLabel, String msg) {
this.msgLabel = msgLabel;
this.msg = msg;
}
#Override
public void actionPerformed(ActionEvent e) {
msgLabel.setText(msg);
}
}
}
}
It has better control over the focus requirements depending on your needs...

Categories

Resources